package org.ezplatform.goa.document.service;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.ezplatform.cache.api.system.user.UserCacheCo;
import org.ezplatform.cache.api.system.user.UserCacheManager;
import org.ezplatform.cloud.api.bpm.BpmApiService;
import org.ezplatform.cloud.api.component.attachment.AttachmentUtilsService;
import org.ezplatform.cloud.api.component.bizcode.BizcodeApiService;
import org.ezplatform.cloud.api.component.fileview.FiletransformApiSevice;
import org.ezplatform.cloud.api.component.goldgrid.GoldgridApiSevice;
import org.ezplatform.cloud.api.model.formmgr.FormApiService;
import org.ezplatform.cloud.api.system.org.OrgApiService;
import org.ezplatform.cloud.api.system.user.UserApiService;
import org.ezplatform.cloud.common.client.RestClient;
import org.ezplatform.cloud.common.log.LogService;
import org.ezplatform.component.permission.service.CmpApplyScopeService;
import org.ezplatform.component.permission.service.CmpPermissionService;
import org.ezplatform.component.permission.utils.CmpPermissionConstant;
import org.ezplatform.component.util.SqlCondiInUtil;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.dao.jpa.JpaBaseDao;
import org.ezplatform.core.pagination.PropertyFilter;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.core.web.view.OperationResult;
import org.ezplatform.goa.common.util.GoaCommonUtil;
import org.ezplatform.goa.document.cache.GovCacheManager;
import org.ezplatform.goa.document.constant.LogConstant;
import org.ezplatform.goa.document.constant.RightConstant;
import org.ezplatform.goa.document.dao.*;
import org.ezplatform.goa.document.entity.*;
import org.ezplatform.goa.document.util.CopyFileUtils;
import org.ezplatform.goa.document.util.DocumentSecUtils;
import org.ezplatform.goa.document.util.DocumentUtils;
import org.ezplatform.goa.document.util.GoaCommonUtils;
import org.ezplatform.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 发起公文流程service逻辑
 * @author gexiang
 *
 */
@Service("GovSendFileService")
@Transactional
public class GovSendFileService extends BaseService<GovSendFile, String>{

	private final Logger logger =  LoggerFactory.getLogger(GovSendFileService.class);
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	@Autowired
	private GovSendFileDao govSendFileDao;

	@Autowired
	private GovLayoutFileDao govLayoutFileDao;

	@Autowired
	private GovSendFileNumDao govSendFileNumDao;

	@Autowired
    private CmpPermissionService cmpPermissionService;

	@Autowired
	private GovScrapBoxService govScrapBoxService;

	@Autowired
	private DocSendReserveFilenoDao sendReseverFileNoDao;

	@Autowired
	private RestClient restClient;

	@Autowired
	private GovCollectionDao govCollectionDao;

	@Autowired
	private GovMyAttentionDao govMyAttentionDao;

	@Autowired
	private GovDistributeRecordService govDistributeRecordService;

	@Autowired
	private GovDistributeUserService disService;

	@Autowired
	private GovDistributeRecordDao govDistributeRecordDao;

	@Autowired
	private GovFlowBackDao govFlowBackDao;

	@Autowired
	private GovSendFileNumService govSendFileNumService;

	@Autowired
	private GovSendGroupFileService govSendGroupFileService;

	@Autowired
	private CopyFileUtils copyFileUtils;

	@Autowired
	private GovDocFileEditionService fileEditionService;

	@Autowired
	private AttachmentUtilsService attachmentUtilsService;

	@Autowired
	@Lazy
	private GovDocAttachmentService govDocAttachmentService;

	@Autowired
	@Lazy
	private GovRelRecordService govRelRecordService;

	@Autowired
	private LogService logService;

	@Autowired
	private GovDocAttachmentDao govDocAttachmentDao;

	@Autowired
	private GovDocHandlingService govDocHandlingService;

	@Autowired
	private GoaCommonUtils goaCommonUtils;

	/*@Autowired
	@Lazy
	private GovSendFileService govSendFileService;*/

	@Autowired
	private GovDistributeUserService disUserService;

	@Autowired
	private GovRegisterRecordService goaDocRegisterRecordService;

	@Autowired
	private CmpApplyScopeService cmpApplyScopeService;

	@Autowired
	@Lazy
	private GovDocReceiveFileService govDocReceiveFileService;

	@Autowired
	@Lazy
	private DocSignreportService docSignreportService;

	@Autowired
	@Lazy
	private GovRegisterService govRegisterService;

	@Autowired
	private GovSendSaveFileNoService govSendSaveFileNoService;

	@Autowired
	private UserApiService userApiService;

	@Autowired
	private GoaDocBizcodeProcessService goaDocBizcodeProcessService;

	@Autowired
    private SignQueryDao signQuery;

	@Autowired
	private GovCacheManager govCacheManager;

	@Autowired
   	private GovBaseSetService govBaseSetService;

	@Autowired
	private DocumentSecUtils documentSecUtils;

    @Autowired
    private BpmApiService bpmApiService;

    @Autowired
    private BizcodeApiService bizcodeApiService;

    @Autowired
    private GoldgridApiSevice goldgridApiSevice;

    @Autowired
    private FormApiService formApiService;

	@Autowired
	private OrgApiService orgApiService;

	@Autowired
	@Lazy
	private GovFullSearchService govFullSearchService;

	@Autowired
	private GoaCommonUtil goaCommonUtil;

	@Autowired
	private UserCacheManager userCacheManager;

	@Autowired
	private FiletransformApiSevice filetransformApiSevice;

	@Autowired
	@Lazy
	private GoaDocSignApproveFileService signApproveFileService;

	@Override
	protected JpaBaseDao<GovSendFile, String> getEntityDao() {
		return govSendFileDao;
	}


	/**
	 * 获取传入文号的，最近的流水号
	 * @param fileNoId
	 * @param corpId
	 * @param startNo
	 * @param year
	 * @param showName
	 * @param showYear
	 * @param showReset
	 * @return
	 */
	public String getNoByFileNo(String fileNoId, String year, String corpId, Long startNo,
			int showName, int showYear, int showReset) {
		List<String> fileNoIds = new ArrayList<>();
		if (StringUtils.isNotEmpty(fileNoId)) {
			GovSendFileNum sendFileNum = govSendFileNumService.findOne(fileNoId);
			String filenoGroupId = sendFileNum.getFilenoGroupId();
			if (StringUtils.isNotEmpty(filenoGroupId)) {
				DocSendFilegroup sendFilegroup = govSendGroupFileService.findOne(filenoGroupId);
				String filenoGroupAllid = sendFilegroup.getFilenoGroupAllid();
				if (StringUtils.isNotEmpty(filenoGroupAllid)) {
					String[] fileids = filenoGroupAllid.split(",");
					fileNoIds = Arrays.asList(fileids);
				}
			}
		}
	        //根据是否跨年重排来判断是否根据年份来查询。
	        //是跨年重排，查询跨年重排的数据
	        String maxFileNo = "";
	        Integer nextFileNum = 1;
	        /*if(1==showReset) {
	        	List<DocSendSavefileno> filenos = this.govSendFileNumDao.getUseFileNoList(Integer.valueOf(year), fileNoId, corpId);
	        	if (filenos != null && filenos.size() > 0) {
	        		DocSendSavefileno  useFileNo = filenos.get(0);
	        		maxFileNo = useFileNo.getUseFileNo()+"";
	        	}
	        	 maxFileNo =   this.govSendFileNumDao.getMaxUseFileNo(fileNoId, corpId,Integer.valueOf(year));
	        }else {
	        	//否则只查询该文号当前使用的最大值
	        	 maxFileNo = this.govSendFileNumDao.getMaxUseFileNo(fileNoId, corpId,Integer.valueOf(year));
	        }*/
		if (CollectionUtils.isNotEmpty(fileNoIds)){
			maxFileNo = this.govSendFileNumDao.getMaxUseFileNos(fileNoIds, corpId, Integer.valueOf(year));
		}else {
			maxFileNo = this.govSendFileNumDao.getMaxUseFileNo(fileNoId, corpId, Integer.valueOf(year));
		}
	        if(StringUtils.isNotBlank(maxFileNo) && !"null".equals(maxFileNo)) {
	        	nextFileNum = Integer.valueOf(maxFileNo)+1;
	        }
	        //查询预留文号列表
	        List<DocSendReserveFileno> list = sendReseverFileNoDao.getReserveFileNoFileNoList(Integer.valueOf(year),fileNoId, corpId);
	        //判断此最大文号是否在预留文号中。
	        if(!list.isEmpty() && list.size()>0) {
	        	Integer maxYlmh = list.get(0).getCurrentNo();
	        	List<Integer> ylwhValueList = new ArrayList<Integer>();
	        	for (DocSendReserveFileno reserveFileno : list) {
	        		Integer currentNo = reserveFileno.getCurrentNo();
	        		ylwhValueList.add(currentNo);
	        	}
	        	Boolean hascontains = false;//默认不包含
					for (int j = nextFileNum; j <=maxYlmh; j++) {
						for (int i = 0; i < ylwhValueList.size(); i++) {
							if(ylwhValueList.contains(j)) {
								nextFileNum = j+1;
								hascontains = true;
								break;
							}
						}
						if(!hascontains) {
							break;
						}
				}
	        	/*for (int i = nextFileNum; i <= maxYlmh; i++) {
	        		if(!ylwhValueList.contains(i)) {
	        			nextFileNum= i;
	        			break;
	        		}
	        	}*/
	        }
	        return nextFileNum.toString();
	}



	/**
	 * 公文统计-办件量统计-获取办件量用户
	 * @Title: getDealcountStatisticList
	 * @param pageable
	 * @param buildFilters
	 * @param corpId
	 * @param orgName
	 * @param userName
	 * @author xuwl
	 * @date 2019-11-11 10:26:35 AM 
	 */
	public Page<Map> getDealcountStatisticList(Pageable pageable, List<PropertyFilter> buildFilters, String corpId,
			String orgName, String userName) {
		StringBuffer sql = new StringBuffer();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("corpId", corpId);
        sql.append(" select u.id as userId,u.user_name as userName,o.org_name as orgName,o.id as orgId  ");
        sql.append(" FROM sys_user u   ");
        sql.append(" LEFT JOIN sys_org_user ou on ou.user_id = u.id and ou.isMain = 1  ");
        sql.append(" LEFT JOIN sys_org o on o.id = ou.org_id and o.is_delete = '0'   ");
        sql.append(" where u.corp_id =:corpId and u.is_delete = '0'    ");

        if (StringUtils.isNotBlank(orgName)) {
            sql.append(" and o.org_name like :orgName ");
            paramMap.put("orgName", "%" + orgName + "%");
        }

        if (StringUtils.isNotBlank(userName)) {
            sql.append(" and u.user_name like :userName ");
            paramMap.put("userName", "%" + userName + "%");
        }
        /*****************添加权限begin by xuwenl***************/
		WebUser user = WebUtils.getCurrentUser();
		String  permission = cmpPermissionService.getBusinessScopeSql("t", user, RightConstant.DOCUMENT_ANALYSIS_VIEW);
		sql.append(permission);
		/*****************添加权限end by xuwenl***************/
        sql.append(" order by o.org_type asc,o.org_name,u.createdDate,u.user_name ");
        String strSql = PropertyFilter.getSqlByFilterAndPageable("u", sql.toString(), " ", buildFilters, pageable);
        Page<Map> page = super.findByPageNativeSQL(pageable, strSql, paramMap);
		return page;
	}


	/**
	 * 判断当前传入的流水号是否已经被使用，或者被预留
	 * @param fileNoId
	 * @param useFileNo
	 * @param year
	 * @param corpId
	 * @return
	 */
	public String checkCurrentFileNo(String fileNoId, String useFileNo, String year, String corpId) {
		// 判断发文字号是否为共用文号 start
		List<String> fileNoIds = new ArrayList<>();
		if (StringUtils.isNotEmpty(fileNoId)) {
			GovSendFileNum sendFileNum = govSendFileNumService.findOne(fileNoId);
			String filenoGroupId = sendFileNum.getFilenoGroupId();
			if (StringUtils.isNotEmpty(filenoGroupId)) {
				DocSendFilegroup sendFilegroup = govSendGroupFileService.findOne(filenoGroupId);
				String filenoGroupAllid = sendFilegroup.getFilenoGroupAllid();
				if (StringUtils.isNotEmpty(filenoGroupAllid)) {
					String[] fileids = filenoGroupAllid.split(",");
					fileNoIds = Arrays.asList(fileids);
				}
			}
		}
		if (fileNoIds.size() > 0 && StringUtils.isNotBlank(useFileNo) && StringUtils.isNotBlank(year)) {
			String type = "0";// 默认可以使用当前传入的文号
			String isUseInfo = govSendFileNumDao.checkUseFileNos(fileNoIds, useFileNo, year, corpId);
			if (!"0".equals(isUseInfo)) {
				type = "1";// 0是代表没有查到，大于0代表重复
			}
			return type;
		} else {
			String type = "0";// 默认可以使用当前传入的文号

			Integer useFileNoInt = Integer.parseInt(useFileNo) ;
			Integer yearInt = Integer.parseInt(year) ;
			String isUseInfo = govSendFileNumDao.checkUseFileNo(fileNoId, useFileNoInt, yearInt, corpId);
			if (!"0".equals(isUseInfo)) {
				type = "1";// 0是代表没有查到，大于0代表重复
			}
			return type;
		}
		// 判断发文字号是否为共用文号 end

		/*
		 * String isReserveInfo =
		 * sendReseverFileNoDao.checkReserveFileNo(fileNoId,useFileNo,year,corpId);
		 * if(!isReserveInfo.equals("0")) { type = "2";//0是代表没有查到，大于0代表重复 }
		 */

	}
	/**
	 * 公文统计-领导文件统计-获取领导列表  
	 * @Title: getLeaderDealcountStatisticList
	 * @param pageable
	 * @param buildFilters
	 * @param corpId
	 * @param orgName
	 * @param userName
	 * @author xuwl
	 * @date 2019-11-13 9:38:09 AM 
	 */
	public Page<Map> getLeaderDealcountStatisticList(Pageable pageable, List<PropertyFilter> buildFilters,
			String corpId, String orgName, String userName) {
		StringBuffer sql = new StringBuffer();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("corpId", corpId);
        sql.append(" select u.id as userId,u.user_name as userName,o.org_name as orgName,o.id as orgId ");
        sql.append(" from goa_leader_set t ");
        sql.append(" left join goa_leader_set_scope s on t.leader = s.fielddatavalue and fielddata = 'leader' ");
        sql.append(" left join sys_user u on s.scopevalue = u.id ");
        sql.append(" LEFT JOIN sys_org_user ou on ou.user_id = u.id and ou.isMain = 1 ");
        sql.append(" left join sys_org o on o.id = u.org_id and o.is_delete = '0' ");
        sql.append(" where u.corp_id =:corpId and u.is_delete = '0'    ");

        if (StringUtils.isNotBlank(orgName)) {
            sql.append(" and o.org_name like :orgName ");
            paramMap.put("orgName", "%" + orgName + "%");
        }

        if (StringUtils.isNotBlank(userName)) {
            sql.append(" and u.user_name like :userName ");
            paramMap.put("userName", "%" + userName + "%");
        }

        /*****************添加权限begin by xuwenl***************/
		WebUser user = WebUtils.getCurrentUser();
		String  permission = cmpPermissionService.getBusinessScopeSql("t", user, RightConstant.DOCUMENT_ANALYSIS_VIEW);
		sql.append(permission);
		/*****************添加权限end by xuwenl***************/
        sql.append(" order by o.org_type asc,o.org_name,u.createdDate,u.user_name ");
        String strSql = PropertyFilter.getSqlByFilterAndPageable("u", sql.toString(), " ", buildFilters, pageable);
        Page<Map> page = super.findByPageNativeSQL(pageable, strSql, paramMap);
		return page;
	}

	/**
	  * 发文查询列表数据
	 * yzn
	 * @param pageable
	 * @param corpId
	 * @param map
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Page getList(Pageable pageable, List<PropertyFilter> buildFilters, String corpId, Map<String, String> map) {
		logger.info("发文查询开始=====================");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		WebUser user = WebUtils.getCurrentUser();
		StringBuffer sql = new StringBuffer();
		StringBuffer fieldSql = new StringBuffer();
		Long start = System.currentTimeMillis();
		List<String> listOfInstId = new ArrayList<>();
		List<GovBaseSet> baseSetList = govCacheManager.getGovBaseInfoCache();
		if(baseSetList == null ) {
			baseSetList = govBaseSetService.findAll();
			govCacheManager.setGovBaseInfoCache(baseSetList);
		}
		GovBaseSet govBaseSet = new GovBaseSet();
		if (baseSetList != null && !baseSetList.isEmpty()){
			govBaseSet = baseSetList.get(0);
		}
		//公文查询改造		
		//sql.append("select temp.* ");
		//sql.append("from (");
		String docSearch = govBaseSet.getDocSearch() !=null ?govBaseSet.getDocSearch().toString() :"";

		//归档sql
		String  selectGdSql = "";
		String  gdSql = "";
		//发文机关sql 
		String  selectFwjgSql = "";
		String  fwjgSql = "";

		String opSql = "";
		String opManSql = "";

		if(StringUtils.isNotBlank(map.get("archiveStatus"))&&!map.get("archiveStatus").equals("undefined")) {
			selectGdSql = ",arc.archive_status as archiveStatus,arc.process_instance_id as processid,arc.form_data_html_attid as formhtmlid,arc.form_data_ofd_attid as formofdattid ";
			gdSql = " left join bpm_process_archive arc on arc.process_instance_id=ahp.proc_inst_id_ ";
		}
		if((false && docSearch.contains("6"))||StringUtils.isNotEmpty(map.get("commentsSearch")) ) {
			opSql = " left join bpm_process_comment brc on brc.processinstance_id=ahp.proc_inst_id_  ";
		}
		if((false && docSearch.contains("5"))||StringUtils.isNotEmpty(map.get("operatorSearchMan")) ) {
			opManSql = " LEFT JOIN act_hi_taskinst ath ON ath.PROC_INST_ID_ = ahp.proc_inst_id_  LEFT JOIN sys_user su ON ath.ASSIGNEE_ = su.id  ";
		}
		/*sql.append(" select z.id,z.signApproveId,z.issuedNumber,z.title,z.filenum,z.userName,z.createdDate,z.flow_status ,z.createdOrg,z.createdBy,z.emergencyDegree,z.proc_inst_id_,z.processInstanceId ,z.attachment,z.formatFile,z.dealStatus ,z.delete_reason_,z.fileContent,z.ext_prewarningdate,z.ext_warningdate ," +
				"z.extUrgentField,z.end_time_,z.security_classification,z.issuing_agency,z.emergency_degree,z.isFiling,z.formid from ( ");*/
		fieldSql.append(" select t.id,t.sign_approve_id as signApproveId,t.file_no_see as issuedNumber ,t.issued_number,ahp.ext_title as title,ahp.ext_startusername as userName, t.createdDate,t.flow_status ,");
		fieldSql.append("t.createdOrg,t.createdBy,t.emergency_degree as emergencyDegree,ahp.proc_inst_id_,ahp.proc_inst_id_ as processInstanceId ,t.attachment,t.format_file as formatFile,ahp.ext_processstatus as dealStatus ,ahp.delete_reason_,");
		fieldSql.append("t.file_content as fileContent,ahp.ext_prewarningdate,ahp.ext_warningdate ,ahp.EXT_URGENTFIELD as extUrgentField,ahp.end_time_,t.security_classification,t.issuing_agency,t.emergency_degree,t.is_filing AS isFiling,t.formid ");
		fieldSql.append(selectGdSql);
		fieldSql.append(selectFwjgSql);
		fieldSql.append(", 0 as filenum from goa_doc_sendfile t inner join ACT_HI_PROCINST ahp on t.id = ahp.BUSINESS_KEY_ ");
		//发文机关查询
		fieldSql.append(fwjgSql);
		//归档公文查询
		fieldSql.append(gdSql);
		//批示意见查询
		fieldSql.append(opSql);
		//经办人查询
		fieldSql.append(opManSql);
		fieldSql.append(" where ahp.BUSINESS_KEY_ in (:businessKeys)");

		sql.append("select t.id from goa_doc_sendfile t ");
		sql.append(" inner join ACT_HI_PROCINST ahp on t.id = ahp.BUSINESS_KEY_  and ahp.EXT_CATEGORY = 'goa_doc_sendfile' ");
		//发文机关查询
		sql.append(fwjgSql);
		//归档公文查询
		sql.append(gdSql);
		//批示意见查询
		sql.append(opSql);
		//经办人查询
		sql.append(opManSql);
		String type = GlobalConstant.getDbType();
		if("ORACLE".equals(type.toUpperCase()) || "DM".equals(type.toUpperCase())) {
			sql.append("where (case when flow_status =1 then 1 when flow_status=2 then 1 when flow_status=3 then 1 when flow_status=4 then 1 when flow_status=5 then 1 end) =1 ");
    	}else {
    		sql.append("where  t.flow_status  in ('1','2','3','4','5') ");
    	}

		if (StringUtils.isNotBlank(map.get("nowDealMan"))) {
			listOfInstId = getInstIdByNowDealName(map.get("nowDealMan"));
			if (listOfInstId != null && listOfInstId.size() > 0) {
				sql.append(" AND ").append(SqlCondiInUtil.processCondiIn("ahp.PROC_INST_ID_",listOfInstId,paramMap));
			} else {
				sql.append(" and 1>2");
			}
		}
        if (StringUtils.isNotBlank(map.get("title"))) {
            //标题多关键词模糊查询
            String[] titleArray = map.get("title").split(",");
            if (titleArray.length > 1) {
                sql.append(" and (");
                for (int i = 0; i < titleArray.length; i++) {
                    sql.append(" ahp.ext_title like :title"+i +" escape '/' ") ;
                    if (i < titleArray.length - 1) {
                        sql.append(" or ");
                    }
                    String titleStr = StringUtils.null2String(titleArray[i]);
					titleStr = titleStr.replace("%","/%");
                    //titleStr = ParamEscapeUtil.unescape(titleStr);
                    paramMap.put("title"+i, "%" + titleStr + "%");
                }
                sql.append(" )");
            } else {
                sql.append("  and (ahp.ext_title like :title escape '/' ) ");
                String titleStr = StringUtils.null2String(map.get("title"));
				titleStr = titleStr.replace("%","/%");
               // titleStr = ParamEscapeUtil.unescape(titleStr);
                paramMap.put("title", "%" + titleStr + "%");
            }
        }
		if(StringUtils.isNotBlank(map.get("issuedNumber"))) {
			sql.append(" and t.file_no_see like :issuedNumber ");
			paramMap.put("issuedNumber", "%"+map.get("issuedNumber")+"%");
		}
		if(StringUtils.isNotBlank(map.get("dealStatus")) && !"6".equals(map.get("dealStatus"))) {
			sql.append(" and ahp.ext_processstatus = :dealStatus ");
			paramMap.put("dealStatus", map.get("dealStatus"));
			if ("2".equals(map.get("dealStatus"))){
				sql.append(" and (ahp.DELETE_REASON_  is NULL OR ahp.DELETE_REASON_ != '强制结束') ");
			}
		}else if("6".equals(map.get("dealStatus"))){
			sql.append(" and ahp.ext_processstatus='2' and ahp.delete_reason_='强制结束' ");
		}
		if(docSearch.contains("1")) {
			//归档查询
			String archiveStatus = map.get("archiveStatus");
			if (StringUtils.isNotEmpty(map.get("archiveStatus"))&&!archiveStatus.equals("undefined")) {
				if ("0".equals(map.get("archiveStatus"))) {
					sql.append(" and arc.archive_status is null  ");
				} else {
					sql.append(" and arc.archive_status like :archiveStatus  ");
					paramMap.put("archiveStatus", map.get("archiveStatus"));
				}
			}
		}
		//经办人
		if(StringUtils.isNotBlank(map.get("operatorSearchMan"))) {
				sql.append(" and su.user_name  like :operatorSearchMan ");
				paramMap.put("operatorSearchMan", "%"+map.get("operatorSearchMan") + "%");
		}

		//批示意见
		if(StringUtils.isNotBlank(map.get("commentsSearch"))) {
				sql.append(" and ( brc.content like :commentsSearch or brc.user_name like :commentsSearch  )");
				paramMap.put("commentsSearch", "%"+map.get("commentsSearch") + "%");
		}

		if(StringUtils.isNotBlank(map.get("processName"))) {
			sql.append(" and t.processName like :processName ");
			paramMap.put("processName", "%"+map.get("processName") + "%");
		}
		if(StringUtils.isNotBlank(map.get("processCode"))) {
			sql.append(" and ahp.EXT_PROCESSCODE =:processCode ");
			paramMap.put("processCode", map.get("processCode"));
		}
		if(StringUtils.isNotBlank(map.get("createName"))) {
			sql.append(" and ahp.ext_startusername like :createName ");
			paramMap.put("createName", "%"+map.get("createName")+"%");
		}
		if(StringUtils.isNotBlank(map.get("startTime"))) {
			sql.append(" and t.createdDate >= :startTime ");
			paramMap.put("startTime", Timestamp.valueOf(map.get("startTime").toString()+" 00:00:00"));
		}
		if(StringUtils.isNotBlank(map.get("endTime"))) {
			sql.append(" and t.createdDate <= :endTime ");
			paramMap.put("endTime", Timestamp.valueOf(map.get("endTime").toString()+" 23:59:59"));
		}
        if (StringUtils.isNotEmpty(map.get("draftingUnit"))) {
			List<String> createOrdIdList = govSendFileDao.findOrgId("%"+map.get("draftingUnit")+"%");
			List<String> issuingAgencyList = govSendFileDao.findIssuingAgencyList("%"+map.get("draftingUnit")+"%");
			if(CollectionUtils.isNotEmpty(issuingAgencyList)){
				if(CollectionUtils.isNotEmpty(createOrdIdList)){
                    if(GlobalConstant.isOracle()){
                        String issuingAgencySql = SqlUtils.getOracleSQLIn(issuingAgencyList,"t.issuing_agency");
                        String createdOrgSql = SqlUtils.getOracleSQLIn(createOrdIdList,"t.createdOrg");
                        sql.append(" and (").append(issuingAgencySql).append(" or ").append(createdOrgSql).append(")");
                    }else{
                        sql.append(" and (t.issuing_agency in (:issuingAgencyList) or (t.createdOrg in (:createOrdIdList) ) ) ");
                        paramMap.put("issuingAgencyList",issuingAgencyList);
                        paramMap.put("createOrdIdList",createOrdIdList);
                    }
				}else {
					sql.append(" and t.issuing_agency in (:issuingAgencyList) ");
					paramMap.put("issuingAgencyList",issuingAgencyList);
				}
			}else {
				paramMap.put("issuingAgencyList","%"+map.get("draftingUnit")+"%");
				if(CollectionUtils.isNotEmpty(createOrdIdList)){
					sql.append(" and ( t.createdOrg in (:createOrdIdList) or  (t.issuing_agency like :issuingAgencyList ) )");
					paramMap.put("createOrdIdList",createOrdIdList);
				}else {
					sql.append(" and t.issuing_agency like :issuingAgencyList ");
				}
			}
        }
        //发起人组织查询
        if (StringUtils.isNotBlank(map.get("startUserGroupName"))) {
			List<String> startUserOrgIds = govBaseSetService.getStartUserOrgIds(map.get("startUserGroupName"));
			if (CollectionUtils.isNotEmpty(startUserOrgIds)) {
				sql.append(" AND ").append(SqlCondiInUtil.processCondiIn("t.createdOrg",startUserOrgIds,paramMap));
			}else {
				sql.append(" AND 1 = 2 ");
			}
        }

		//是否涉密开启
        Boolean secretFlag = GlobalConstant.isUseSecretLevel();
        if(secretFlag) {
        	//获取当前登录人的涉密登记
        	int secretLevel = user.getSecretLevel();
        	sql.append(" and (t.security_classification >= '"+secretLevel + "' or t.security_classification is null or t.security_classification = '' ) ");
        }

		String  permission = cmpPermissionService.getBusinessScopeSql("t", user, RightConstant.DOCUMENT_SEARCH_VIEW);
	    sql.append(permission);
	    if(docSearch.contains("1") || docSearch.contains("2")) {
	    	 //sql.append("  and  arc.process_instance_id  is not null and  bpf.process_instance_id  is not null  ");
	    }
	    // 排序
        String finalSQL = PropertyFilter.getSqlByFilterAndPageable("t", sql.toString(), "", buildFilters, pageable);
		finalSQL = finalSQL+" order by t.createdDate desc ";
//        if (finalSQL.contains("order by")) {// 排序处理
//            int i = finalSQL.split("order by").length;
//            String orderBy  = finalSQL.split("order by")[1];
//            if(finalSQL.split("order by")[1].indexOf("userName") > -1){
//				orderBy = finalSQL.split("order by")[1].replace("z.userName","ahp.ext_startusername");
//			}
//            if (i > 0) {
//                if (i == 1) {
//                    finalSQL = finalSQL.split("order by")[0] + " order by z.createdDate desc ";
//                } else {
//                    finalSQL = finalSQL.split("order by")[0] + "order by " + orderBy;
//                }
//            }
//        } else {
//            finalSQL += " order by z.createdDate desc ";
//        }
		 // 分页查询
        Page<Map> page = this.findByPageNativeSQL(pageable, finalSQL, paramMap);
		List<Map> list = page.getContent();
		if(null!=list && list.size()>0){
			List<String> businessKeys = new ArrayList();
			for(Map map1 : list){
				businessKeys.add(map1.get("id").toString());
			}
			Map map2 = new HashMap();
			map2.put("businessKeys", businessKeys);
			List<Map> list1 = super.findByListNativeQuery(fieldSql.toString(), "",map2);
			for(Map map1 : list){
				for(Map map3 : list1){
					if(StringUtils.equals(map1.get("id").toString(),map3.get("id").toString())){
						map1.putAll(map3);
					}
				}
			}
		}
		Long end = System.currentTimeMillis();

        //数据范围权限控制，可有多个
        Map<String,String> permissionInfoMap = new HashMap<String,String>();
        //map格式：key-权限编码，value-操作标识
        permissionInfoMap.put(RightConstant.DOCUMENT_SEARCH_UPDATE, CmpPermissionConstant.PERMISSION_NAME_CAN_EDIT);
        permissionInfoMap.put(RightConstant.DOCUMENT_SEARCH_VIEW, CmpPermissionConstant.PERMISSION_NAME_CAN_VIEW);
        permissionInfoMap.put(RightConstant.DOCUMENT_SEARCH_DEL, CmpPermissionConstant.PERMISSION_NAME_CAN_DELETE);
        permissionInfoMap.put(RightConstant.DOCUMENT_SEARCH_END, "canSyn");
        permissionInfoMap.put(RightConstant.DOCUMENT_SEARCH_SYN, "canEnd");
        permissionInfoMap.put(RightConstant.DOCUMENT_SEARCH_GD, "canGD");

        String processInstanceIds = "";
        Long end4 = 0L;
        List<String> procInstIdList = new ArrayList<>();
		logger.error("list------------------->"+list.size());
        if(list!=null&&list.size()>0) {
   			for(int i=0;i<list.size();i++) {
   				Map one = list.get(i);
   				procInstIdList.add(StringUtils.null2String(one.get("proc_inst_id_")));
   				if(one.get("proc_inst_id_")!=null) {
   					processInstanceIds += one.get("proc_inst_id_").toString()+",";
   				}
   				String issuing_agency = StringUtils.null2String(one.get("issuing_agency"));
   				String issuingAgencyName = getIssuingAgency(issuing_agency);
   				list.get(i).put("issuingAgency",issuingAgencyName);
   				//根据基础设置获取发起人组织
                String createdOrg = StringUtils.null2String(one.get("createdOrg"));
                if (StringUtils.isNotBlank(createdOrg)) {
                    String startUserGroupName = govBaseSetService.getOrgShowName(createdOrg);
                    if(StringUtils.isNotBlank(startUserGroupName)){
                        startUserGroupName = startUserGroupName.replace(".","/");
                    }
                    one.put("startUserGroupName", startUserGroupName);
                }
   			}
			logger.error("processInstanceIds---------1111---------->"+processInstanceIds);

			Long end1 = System.currentTimeMillis();
   			if(docSearch.contains("3")) {
   				//关联流程数字查询使用
   				Map<String,List<Map>> relationProcess = govSendGroupFileService.getRelationProcestb(procInstIdList);
   				for(int i=0;i<list.size();i++) {
   					Map one = list.get(i);
   					String proc_inst_id_= StringUtils.null2String(one.get("proc_inst_id_"));
   					boolean flag11 = false;
   					for(String key : relationProcess.keySet()) {
   						List<Map> list2 = relationProcess.get(key);
   						if(proc_inst_id_.equals(key)) {
   							flag11 = true;
   							if(one.containsKey("relationProcessSize")) {
   								one.put("relationProcessSize", list2.size()+(Integer)one.get("relationProcessSize"));
   							}else {
   								one.put("relationProcessSize", list2.size());
   							}
   						}
   					}
   					if(!flag11) {
   						one.put("relationProcessSize", 0);
   					}
   				}
   				Long end2 = System.currentTimeMillis();

   				//相关公文办理情况数字查询使用
   				Map<String,List<Map>> relationgovstates = disService.getRelationGovStates(procInstIdList);
   				for(int i=0;i<list.size();i++) {
   					Map one = list.get(i);
   					String proc_inst_id_= StringUtils.null2String(one.get("proc_inst_id_"));
   					for(String key : relationgovstates.keySet()) {
   						List<Map> list2 = relationgovstates.get(key);
   						if(proc_inst_id_.equals(key)) {
   							if(one.containsKey("relationProcessSize")) {
   								one.put("relationProcessSize", list2.size()+(Integer)one.get("relationProcessSize"));
   							}else {
   								one.put("relationProcessSize", list2.size());
   							}
   						}
   					}
   				}
   				Long end3 = System.currentTimeMillis();

   			}
			Long end6 = System.currentTimeMillis();

   			//处理归档数据
			List<Map> archivInfo = new ArrayList<Map>();
			if((docSearch.contains("1") || docSearch.contains("2")) && StringUtils.isBlankAll(map.get("archiveStatus"))) {
				//获取流程实例对应的归档数据
				archivInfo = this.govSendGroupFileService.getArchivInfo(procInstIdList);
				if(archivInfo!=null&&archivInfo.size()>0) {
					for (Map map1 : list) {
						String proc_inst_id_ = String.valueOf(map1.get("proc_inst_id_"));
						for (Map map2 : archivInfo) {
							String processid = String.valueOf(map2.get("processid"));
							if (processid.equals(proc_inst_id_)) {
								map1.put("archiveStatus", map2.get("archiveStatus"));
								map1.put("processid", processid);
								map1.put("formhtmlid", map2.get("formhtmlid"));
								map1.put("formofdattid", map2.get("formofdattid"));
							}
						}

					}
				}

			}

			if (docSearch.contains("1")) {
				//获取流程实例对应的归档设置
				Map<String, String> proMap = new HashMap<String, String>();
				processInstanceIds = processInstanceIds.replaceAll(",$", "");
				if (StringUtils.isNotEmpty(processInstanceIds)) {
					proMap.put("processInstanceIds", processInstanceIds);
					String processbakTypes = bpmApiService.getProcessbakTypes(proMap, user.getJwtToken());
					Map<String, Object> processbakmap = JsonUtils.readValue(processbakTypes);
					Map dataMap = (Map) processbakmap.get("data");
					//Map processmap = (Map) data.get("map");
					if (dataMap != null && dataMap.size() > 0) {
						for (int i = 0, size = list.size(); i < size; i++) {
							Map tempMap = list.get(i);
							String tempProcessInstanceId = StringUtils.null2String(tempMap.get("proc_inst_id_"));
							if (!tempMap.isEmpty()) {
								tempMap.put("processbakType", dataMap.get(tempProcessInstanceId));
							}
						}
					}
				}
			}
			end4 = System.currentTimeMillis();

        }
   		List<String> businessKeyList = new ArrayList();
   		List<Map> a = new ArrayList<Map>();
   		List<Map> filenumList = new ArrayList<Map>();
		Long end7 = System.currentTimeMillis();
        if(!list.isEmpty()) {
			for (Map map2 : list) {
				String businessKey = (String) map2.get("id");
				businessKeyList.add(businessKey);
				String createdDate =  StringUtils.null2String(map2.get("createdDate"));
				if(!StringUtils.isEmpty(createdDate)) {
					map2.put("createdDate", createdDate.substring(0, 16));
				}
			}
			//对附件数量做单独判断
			String filesql = " select count(*) as filenum, so.document_id from goa_document_attachment so where so.isDelete = 0 " +
                    " and so.document_source = 1 and so.file_source <> 4 and  so.document_id  in (:busniesskey)  group by so.document_id";
			Map paramMap2 = new HashMap();
			paramMap2.put("busniesskey", businessKeyList);
			filenumList = super.findByListNativeQuery(filesql, "",paramMap2);

	   		//2层for循环进行组装
			String sql1 = " select  art.name_ as taskName , art.proc_def_id_ ,lin.user_id_ as userId ,art.assignee_ assignee, art.ext_urgent ," +
					" art.proc_inst_id_,art.id_ "
					+" from  ACT_RU_TASK art  left join act_ru_identitylink  lin on lin.task_id_ =  art.id_"
					+	" where  art.proc_inst_id_ in(:procInstIdList) and art.CATEGORY_ = 'goa_doc_sendfile'";
			Map paramMap1 = new HashMap();
			paramMap1.put("procInstIdList", procInstIdList);
			a = super.findByListNativeQuery(sql1.toString(), "",paramMap1);

        }
        if(filenumList !=null && filenumList.size()>0){
            for(int fi = 0; fi<list.size(); fi++){
                Map  listmap = list.get(fi);
                String id_filenum = "0";
                String id = (String) list.get(fi).get("id");
                for (int T = 0; T < filenumList.size(); T++) {
                    String document_id =  filenumList.get(T).get("document_id").toString();
                    String filenum = String.valueOf(filenumList.get(T).get("filenum"));
                    if(id.equals(document_id)){
                        id_filenum = filenum;
                    }
                }
                listmap.put("filenum", id_filenum);
            }
        }
        for (int j = 0; j < list.size(); j++) {
			Map  listmap = list.get(j);
			String processInstanceId = (String) list.get(j).get("proc_inst_id_");
			String alldealUser  = "";
			String proc_def_id_="";
			String form_key_= (String) list.get(j).get("formid");;
			String proc_inst_id_="";
			String id_="";
			String alldealName="";
			String ext_urgent="";
			for (int L = 0; L < a.size(); L++) {
				String  currentProcId = (String) a.get(L).get("proc_inst_id_");
				String dealUser = (String) a.get(L).get("userId");
				String assignee = (String) a.get(L).get("assignee");
				String dealName = (String) a.get(L).get("taskName");
				ext_urgent = (String) a.get(L).get("ext_urgent");
				String userIdt = assignee;
				if (StringUtils.isEmpty(assignee)) {
					userIdt = dealUser;
				}
				if(StringUtils.isNotBlank(processInstanceId) && processInstanceId.equals(currentProcId)) {
					if(StringUtils.isNotBlank(userIdt)) {
						//通过缓存取出姓名
						UserCacheCo userCache = userCacheManager.getUserCacheById(userIdt,corpId);
						String userName = userCache.getUserName();
						alldealUser+=userName+"|";
						/*String userName= userMap.get(userIdt).toString();
						alldealUser+=userName+"|";*/
					}
					proc_def_id_ = (String) a.get(L).get("proc_def_id_");
					id_ = (String) a.get(L).get("id_");
					if(StringUtils.isNotBlank(dealName)) {
						alldealName+=dealName+"|";
					}
				}
			}
			if(StringUtils.isNotBlank(alldealUser) && alldealUser.length()>0) {
				alldealUser = alldealUser.substring(0,alldealUser.length()-1);
			}
			if(StringUtils.isNotBlank(alldealName) && alldealName.length()>0) {
				alldealName = alldealName.substring(0,alldealName.length()-1);
			}
			listmap.put("assignee", alldealUser);
			listmap.put("proc_def_id_",  proc_def_id_);
			listmap.put("form_key_", form_key_);
			listmap.put("proc_inst_id_", processInstanceId);
			listmap.put("id_", id_);
			listmap.put("dealName", alldealName);
			listmap.put("taskUrgent", ext_urgent);
		}
		Long end8 = System.currentTimeMillis();
        //处理平台的平行越权
        Map<String,String> coedMap = new HashMap<>();
		for (int i = 0; i < list.size(); i++) {
			String id_ = String.valueOf(list.get(i).get("id_"));
			String processInstanceId = String.valueOf(list.get(i).get("processInstanceId"));
			coedMap.put("id",id_);
			coedMap.put("processInstanceId",processInstanceId);
			String encodeMap = DocumentSecUtils.documentListEncodeMap(coedMap);
			list.get(i).put("approvedatacode",encodeMap);
		}
        if(docSearch.contains("1") || docSearch.contains("2")) {
        	List<Map> ofdList = new ArrayList<Map>();
        	if(!list.isEmpty()) {
        		String sql2 = "select aph.business_key_ , bpf.ofd_att_id as ofdAttId  from ACT_HI_PROCINST aph left join bpm_process_formofd bpf "
        				+ "on bpf.process_instance_id = aph.proc_inst_id_ where  aph.business_key_ in(:busniesskey) ";
        		Map paramMap2 = new HashMap();
        		paramMap2.put("busniesskey", businessKeyList);
        		ofdList = super.findByListNativeQuery(sql2.toString(), "",paramMap2);
        	}
        	for (int m = 0; m < list.size(); m++) {
        		Map  listmap = list.get(m);
        		String id = (String) list.get(m).get("id");
        		String businesskey= "";
        		String ofdAttId =  "";
        		for (int M = 0; M < ofdList.size(); M++) {
        			if(id.equals(businesskey)) {
        				businesskey = (String) a.get(M).get("business_key_");
        				ofdAttId = (String) a.get(M).get("ofdAttId");
        			}
        		}
        		listmap.put("ofdAttId", ofdAttId);
        	}
        }
        //处理平行越权问题
	    list = documentSecUtils.documentListEncodeListById(list);

		/*list = DocumentSecUtils.approveListEncodeList(list,"id,processInstanceId","id");*/
		list = cmpPermissionService.processBusinessListByDataScope(list, user, permissionInfoMap );
		return page;
	}

	public String getIssuingAgency(String fieldDataValue){
		String res = "";
		if(fieldDataValue!=null && fieldDataValue.length()>0){
			Map<String, Object> paramMap = new HashMap<String, Object>();
			StringBuffer sql = new StringBuffer();
			sql.append(" SELECT name,fieldDataValue FROM goa_doc_sendfile_scope WHERE  fieldDataValue = :fieldDataValue ");
			paramMap.put("fieldDataValue", fieldDataValue);
			List<Map> list = findByListNativeQuery(sql.toString(), "",paramMap);
			if (list!=null&&list.size()>0) {
				for (Map map : list) {
					String name = StringUtils.null2String(map.get("name"));
					if(name.length()>0){
						res += name+",";
					}
				}
				if(res.endsWith(",")){
					res = res.substring(0,res.length()-1);
				}
			}
		}
		return res;
	}

	/**
	 * 当前输入的办理人查询项，获取流程实例id集合
	 * @param userName
	 * @return
	 */
	public List<String> getInstIdByNowDealName(String userName) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		//WebUser user = WebUtils.getCurrentUser();
		List<String> result = new ArrayList<>();
		StringBuffer sql = new StringBuffer();
		sql.append(" select art.PROC_INST_ID_ as instId ");
		sql.append(" from act_ru_task art ");
		sql.append(" LEFT JOIN act_ru_identitylink lin ON lin.task_id_ = art.id_ ");
		sql.append("left join sys_user su1 on su1.id = lin.user_id_   ");
		sql.append(" left join sys_user su on art.ASSIGNEE_  = su.id ");
		sql.append(" where su.user_name like :userName or su1.user_name like :userName ");
		paramMap.put("userName", "%"+userName+"%");
		List<Map> mapTemp = findByListNativeQuery(sql.toString(), "",paramMap);
		if (mapTemp!=null&&mapTemp.size()>0) {
			for (Map map : mapTemp) {
				result.add(String.valueOf(map.get("instId")));
			}
		}
		return result;
	}


	/**
	 * @param procinstid
	 * @return
	 */
	public Map<String, String> getAssigneeByProcinstid(String procinstid) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		WebUser user = WebUtils.getCurrentUser();
		Map<String, String> result = new HashMap<>();
		StringBuffer sql = new StringBuffer();
		sql.append(" select su.user_name AS dealUser1,su1.user_name AS dealUser2,art.form_key_ ");
		sql.append(" from act_ru_task art ");
		sql.append(" LEFT JOIN act_ru_identitylink lin ON lin.task_id_ = art.id_");
		sql.append(" left join sys_user su on art.ASSIGNEE_  = su.id ");
		sql.append(" LEFT JOIN sys_user su1 ON su1.id = lin.user_id_ ");
		sql.append(" where 1=1 and art.PROC_INST_ID_=:procinstid");
	    paramMap .put("procinstid", procinstid);
	    List<Map> resultlist = findByListNativeQuery(sql.toString(),"",paramMap);
	    String assignee="";
	    if (null!=resultlist&&resultlist.size()>0) {
			for (Map map : resultlist) {
				if (map.get("dealUser1")!=null) {
					assignee+=map.get("dealUser1") +"|";
				}
				if (map.get("dealUser2")!=null) {
					assignee+=map.get("dealUser2") +"|";
				}
				result.put("formKey", String.valueOf(map.get("form_key_")));
			}
		}
		if(StringUtils.isNotEmpty(assignee)){
			assignee = assignee.substring(0, assignee.length()-1);
		}
	   result.put("assignee", assignee);
	   return result;
	}


	/**
	 * 发文量统计
	 * @param pageable
	 * @param corpId
	 * @param fqdw 发文单位
	 * @param fqbm 发文部门
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	public Page<Map> findSendPage(Pageable pageable, String corpId, String fqdw, String fqbm, String startTime, String endTime) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT count(1) as num,g1.org_name AS dept,g2.org_name AS orgName,t.createdOrg AS createdOrg,g1.id deptId, ");
		sql.append(" g1.org_type orgType,g1.sort_no sortNo,g2.org_type departOrgType,g2.sort_no departSortNo ");
		sql.append(" from goa_doc_sendfile t ");
//		sql.append(" LEFT JOIN sys_org g1 ON t.sponsor_unit = g1.id AND g1.is_delete = 0 ");
        //sql.append(" LEFT JOIN act_hi_procinst ahp ON ahp.BUSINESS_KEY_ = t.id ");
        sql.append(" LEFT JOIN sys_org g1 ON t.sponsor_unit = g1.id ");
		sql.append(" LEFT JOIN sys_org g2 ON t.createdOrg = g2.id AND g2.is_delete = 0 ");
		sql.append(" WHERE 1=1 ");
        sql.append(" AND t.flow_status !='6' AND t.flow_status !='7' AND t.flow_status is not null ");
        sql.append(" AND t.createdOrg is not NUll AND t.createdOrg !=' ' ");
		if(StringUtils.isNotBlank(fqdw)) {
			 sql.append(" and g1.org_name like :fqdw ");
			 paramMap.put("fqdw", "%"+fqdw+"%");
		}
		if(StringUtils.isNotBlank(fqbm)) {
			sql.append("and g2.org_name like :fqbm ");
			paramMap.put("fqbm", "%"+fqbm+"%");
		}
		if(StringUtils.isNotBlank(startTime)) {
			sql.append("and t.createdDate >= :startTime ");
			paramMap.put("startTime", Timestamp.valueOf(startTime+" 00:00:00"));
		}
		if(StringUtils.isNotBlank(endTime)) {
			sql.append("and t.createdDate <= :endTime ");
			paramMap.put("endTime", Timestamp.valueOf(endTime+" 23:59:59"));
		}
		WebUser user = WebUtils.getCurrentUser();
		String  permission = cmpPermissionService.getBusinessScopeSql("t", user, RightConstant.DOCUMENT_ANALYSIS_VIEW);
		sql.append(permission);
		sql.append(" GROUP BY g1.org_name,g2.org_name,t.createdOrg,g1.id,g1.org_type,g1.sort_no,g2.org_type,g2.sort_no  ");
		sql.append(" ORDER BY g1.org_type,g1.sort_no,g2.org_type,g2.sort_no,g2.org_name ");
        Page<Map> page = super.findByPageNativeSQL(pageable, sql.toString(), paramMap);
        /*List<Map> resultList = page.getContent();
        for(Map dataMap : resultList){
        	String dept = dataMap.get("dept") + "";
			if(!StringUtils.isNotBlank(dept) || "null".equals(dept) || "NULL".equals(dept)){
				String orgName = orgApiService.getInstitutionByOrgId(dataMap.get("createdOrg") + "",user.getJwtToken()).get("orgName") + "";
				String orgId = orgApiService.getInstitutionByOrgId(dataMap.get("createdOrg") + "",user.getJwtToken()).get("id") + "";
				dataMap.put("dept",orgName);
				dataMap.put("deptId",orgId);
			}
		}*/
        return page;
	}

	/**
	 * 获取发文统计下钻数据
	 * @param pageable
	 * @param corpId
	 * @param processName
	 * @param orgid
	 * @return
	 */
	public Page<Map> findSendPageTwo(Pageable pageable, String corpId, String processName, String orgid,String startTime,
		      String endTime,String deptId) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        StringBuffer sql = new StringBuffer();
        //sql.append("select c.org_name as orgName,t.process_name as processName,count(1) as num ");
        sql.append("select c.org_name as orgName,bd.process_name as processName,count(1) as num,bd.sort_no,bd.createdDate ");
        sql.append("from goa_doc_sendfile t ");
        sql.append("left join sys_org c on t.createdOrg = c.id and c.is_delete = 0 ");
		sql.append("left join act_hi_procinst p on t.id = p.BUSINESS_KEY_ ");
		sql.append("left join act_re_procdef d on p.PROC_DEF_ID_ = d.id_ ");
		sql.append("left join bpm_process_define bd on d.key_ = bd.process_code ");
        sql.append("where 1=1 and bd.id is not null ");
        sql.append(" AND t.flow_status !='6' AND t.flow_status !='7' AND t.flow_status is not null ");
        if(StringUtils.isNotBlank(deptId)){
            sql.append(" AND t.sponsor_unit = :deptId ");
            paramMap.put("deptId",deptId);
        }
        if(StringUtils.isNotBlank(processName)) {
                sql.append("and bd.process_name like :processName ");
                paramMap.put("processName", "%"+processName+"%");
        }
        if(StringUtils.isNotBlank(orgid)) {
                sql.append("and t.createdOrg = :createdOrg ");
                paramMap.put("createdOrg", orgid);
        }
        if(StringUtils.isNotBlank(startTime)) {
           sql.append("and t.createdDate >= :startTime ");
//           if(GlobalConstant.isABase()) {
				paramMap.put("startTime", Timestamp.valueOf(startTime+" 00:00:00"));
//           }else {
//				paramMap.put("startTime", startTime+" 00:00:00");
//           }
        }
        if(StringUtils.isNotBlank(endTime)) {
            sql.append("and t.createdDate <= :endTime ");
//            if(GlobalConstant.isABase()) {
				paramMap.put("endTime", Timestamp.valueOf(endTime+" 23:59:59"));
//			}else {
//				paramMap.put("endTime", endTime+" 23:59:59");
//			}
        }
        /*****************添加权限begin by xuwenl***************/
  		WebUser user = WebUtils.getCurrentUser();
  		String  permission = cmpPermissionService.getBusinessScopeSql("t", user, RightConstant.DOCUMENT_ANALYSIS_VIEW);
  		sql.append(permission);
  		/*****************添加权限end by xuwenl***************/
        //sql.append(" GROUP BY t.process_name ");
  		sql.append(" GROUP BY bd.process_name,c.org_name,bd.sort_no,bd.createdDate ");
        sql.append(" ORDER BY bd.sort_no asc,bd.createdDate desc ");

        logger.info("sql2=============================================="+sql.toString());
        logger.info("paramMap2========================================="+paramMap);
        return super.findByPageNativeSQL(pageable, sql.toString(), paramMap);
	}

	/**
	 * @Title: findSignReportPageThree
	 * @param pageable
	 * @param corpId
	 * @param processName
	 * @param userName
	 * @return
	 * @author sh
	 * @date 2019-11-07 8:26:12 PM 
	 */
	public Page<Map> findSendPageThree(Pageable pageable, String corpId, String processName, String userName,String orgid,String startTime,String endTime) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		StringBuffer sql = new StringBuffer();
		//sql.append("select b.user_name as userName,t.process_name_sta as processName,count(1) as num ");
		sql.append("select b.user_name as userName,bd.process_name as processName,count(1) as num,b.sort_no ");
		sql.append("from goa_doc_sendfile t ");
		sql.append("left join sys_user b on t.createdBy = b.id and b.is_delete = 0 ");
		sql.append(" left join act_hi_procinst p on t.id = p.BUSINESS_KEY_  ");
		sql.append(" left join act_re_procdef d on p.PROC_DEF_ID_ = d.id_ ");
		sql.append(" left join bpm_process_define bd on d.key_ = bd.process_code  ");
		sql.append("where 1=1 and bd.id is not null ");
        sql.append(" AND t.flow_status !='6' AND t.flow_status !='7' AND t.flow_status is not null ");
		if(StringUtils.isNotBlank(userName)) {
			sql.append("and b.user_name like :userName ");
			paramMap.put("userName", "%"+userName+"%");
		}
		if(StringUtils.isNotBlank(processName)) {
			//sql.append("and t.process_name_sta = :processName ");
			sql.append("and bd.process_name = :processName ");
			paramMap.put("processName", processName);
		}
		if(StringUtils.isNotBlank(orgid)) {
			sql.append("and t.createdOrg = :createdOrg ");
			paramMap.put("createdOrg", orgid);
		}
		if(StringUtils.isNotBlank(startTime)) {
            sql.append("and t.createdDate >= :startTime ");
//            if(GlobalConstant.isABase()) {
            	paramMap.put("startTime", Timestamp.valueOf(startTime+" 00:00:00"));
//            }else {
//            	paramMap.put("startTime", startTime+" 00:00:00");
//            }
		}
		if(StringUtils.isNotBlank(endTime)) {
            sql.append("and t.createdDate <= :endTime ");
//            if(GlobalConstant.isABase()) {
            	paramMap.put("endTime", Timestamp.valueOf(endTime+" 23:59:59"));
//            }else {
//            	paramMap.put("endTime", endTime+" 23:59:59");
//            }
		}
		/*****************添加权限begin by xuwenl***************/
  		WebUser user = WebUtils.getCurrentUser();
  		String  permission = cmpPermissionService.getBusinessScopeSql("t", user, RightConstant.DOCUMENT_ANALYSIS_VIEW);
  		sql.append(permission);
  		/*****************添加权限end by xuwenl***************/
		sql.append(" GROUP BY t.createdBy,b.user_name,bd.process_name,b.sort_no ");
		sql.append(" ORDER BY b.sort_no asc ");

		logger.info("sql3=============================================="+sql.toString());
        logger.info("paramMap3========================================="+paramMap);

		return super.findByPageNativeSQL(pageable, sql.toString(), paramMap);
	}

	/**
	  * 根据发文id查询发文字号
	 * @param id
	 * @return
	 */
	public String getFileNoBySendFileId(String id) {
		String fileNo = StringUtils.EMPTY;
		GovSendFile sendfile = super.findOne(id);
		if(sendfile !=null) {
			fileNo = sendfile.getIssuedNumber();
		}
		return fileNo;
	}

	/**
	 * 删除
	 * @param ids
	 * @return
	 */
	public OperationResult delete(String ids, String processInstanceId, WebUser user, String corpId, String token) {
		try {
			if(StringUtils.isNotEmpty(ids)) {
				List<String> list = new ArrayList<String>();
				String[] split = ids.split(",");
				for (int i = 0; i < split.length; i++) {
					GovDocdelrecord delRecord = new GovDocdelrecord();
					GovSendFile findOne = this.findOne(split[i]);
					delRecord.setBusinesskey(split[i]);
					delRecord.setBusinesstable("goa_doc_sendfile");
					delRecord.setTitle(findOne.getTitle());
					delRecord.setDocnum(findOne.getFileNoSee());
					delRecord.setBusinessCreateUser(findOne.getCreatedBy());
					delRecord.setBusinessCreateOrg(findOne.getCreatedOrg());
					delRecord.setSecretLevel(findOne.getSecurityClassification());
					delRecord.setFlowStatus(findOne.getFlowStatus());
					delRecord.setProcessInstanceId(processInstanceId);
					delRecord.setFileNoName(findOne.getFileNoSee());
					govScrapBoxService.save(delRecord);//保存删除记录
					findOne.setBlnDelete("1");
					//findOne.setFlowStatus("6");
					this.save(findOne);
					String savefilenoId = findOne.getSavefilenoId();

					//删去goa_doc_send_savefileno 表中对应的字号共用组的字号
					if(StringUtils.isNotEmpty(savefilenoId)){
						List<Map> groupInfo = govSendFileNumDao.getGroupInfoById(savefilenoId);
						if(groupInfo!=null && groupInfo.size()>0) {
							for(int j = 0 ;j < groupInfo.size();j++ ){
								Map groupMap = groupInfo.get(j);
								String usename = StringUtils.null2String(groupMap.get("usename"));
								String year = StringUtils.null2String(groupMap.get("year"));
								String useFileNo = StringUtils.null2String(groupMap.get("use_file_no"));
								List<String> groupIds = this.getGroupIdByInfo(usename,year,useFileNo);
								if (groupIds != null && groupIds.size() > 0){
									for(int k = 0; k < groupIds.size();k++){
										govSendFileDao.deleteSaveFileNoById(groupIds.get(k));
									}

								}
							}

						}
					}
					govSendFileDao.deleteByIds(split[i]);
					//govSendFileDao.updateSaveFileNoStatus(findOne.getIssuedNumber());
					if (StringUtils.isNotBlank(findOne.getFileNoSee())) {
						govSendFileDao.deleteSaveFileNo(findOne.getFileNoSee());
					}
					if (StringUtils.isNotBlank(savefilenoId)){
						govSendFileDao.deleteSaveFileNoById(savefilenoId);
					}

					// 更新goa_doc_send_reserve_fileno状态
					String str = findOne.getIssuedNumber();
					String newwh = "";
					String newStr = "";
					String jgdz = "";
					String nf  = "";
				    String hm = "";
					//机关带子，年份，号码
				    if (null!=str) {
				    	if(str.indexOf("]")>-1){//不显示文号名
							newStr = str.split("]")[1];
							jgdz = str.split("]")[0].replace("[","");
							if(newStr.indexOf('-')>-1){//不显示年份
								nf = newStr.split("-")[1];
								hm=	newStr.split("-")[2];
								if (hm.indexOf("|") > -1) {
				    				hm=	hm.split("\\|")[1];
								}
							}else {
								hm = newStr.split("〕")[1];
								if (hm.indexOf("|") > -1) {
				    				hm=	hm.split("\\|")[1];
								}
								nf=	newStr.split("〕")[0].split("〔")[1];
							}
						}else if(str.indexOf(')')>-1){//显示文号名
							jgdz = str.split("\\)")[0].replace("(","");
							newStr = str.split("\\)")[1];
							if(newStr.indexOf('-')>-1){//不显示年份
								nf = newStr.split("-")[1];
								hm=	newStr.split("-")[2];
								if (hm.indexOf("|") > -1) {
				    				hm=	hm.split("\\|")[1];
								}
							}else {
								hm = newStr.split("〕")[1];
								if (hm.indexOf("|") > -1) {
				    				hm=	hm.split("\\|")[1];
								}
				    			nf=	newStr.split("〕")[0].split("〔")[1];
							}
						}else{
							newStr = str;
						}
				    	newwh = jgdz+"〔"+nf+"〕"+hm;
					}

					if(StringUtils.isNotBlank(newwh)) {
						govSendFileDao.deleteReserveFileNo(newwh);
						govSendFileDao.deleteSaveFileNo(newwh);
						newwh += "号";//在我的发起中取消，导致发文字号发生变化，需重新组合后删除
						govSendFileDao.deleteSaveFileNo(newwh);
					}

					list.add(split[i]);
					// 判断这条数据是分发、转发、转阅、还是传阅
					List<Map<String, String>> queryMaps = govDistributeRecordDao.queryDistributeUserAndRecord(split[i]);
					if (queryMaps != null && queryMaps.size() > 0) {
						for (Map<String, String> itemMap : queryMaps) {
							String source = itemMap.get("source");
							String receive_user_idstr = itemMap.get("receive_user_idstr");
							String dataId = itemMap.get("id");
							if ("3".equals(source) || "4".equals(source)) {
								// 删除统一消息来自转阅、传阅的待阅列表数据
								String[] recArr = receive_user_idstr.split(",");
								String msgReceiverStr = "";
								for (String rec : recArr) {
									msgReceiverStr += "{\"10\":\"" + rec + "\"},";
								}
								if (StringUtils.isNotEmpty(msgReceiverStr)) {
									msgReceiverStr = msgReceiverStr.substring(0, msgReceiverStr.length() - 1);
								}
								goaCommonUtils.deleteMessages(dataId, corpId, "[" + msgReceiverStr + "]", user.getJwtToken(),"3");
							}
						}
					}
					//判断这条收藏数据是分发、转发、转阅、还是传阅
					List<Map<String,String>> queryMap = govCollectionDao.queryCollectionDataFromWhere(corpId, split[i]);
					if(queryMap!=null && queryMap.size()>0) {
						for (Map<String, String> itemMap : queryMap) {
							String source = itemMap.get("source");
							String id = itemMap.get("id");
							if("3".equals(source) || "4".equals(source)) {
								//删除收藏夹数据
								govCollectionDao.cancelAllCollectionInfo(id);
							}
						}
					}
					//释放流水号
					releaseBizCode(user,findOne.getId(),findOne.getSerialNumber(),findOne.getBizId(),findOne.getBizShowValue());
					//删除待办，我的发起收藏夹数据
					logger.info("删除收藏夹数据："+ids);
					govCollectionDao.cancelCollectionInfo(corpId, list);
					//删除，待阅，已阅文件
					govDistributeRecordService.deleteDistributeRecord("1", split[i]);
					//删除退回列表数据
					govFlowBackDao.updateBackDataStatus(split[i]);
				}
				//删除关注列表数据
				logger.info("删除关注数据：processInstanceId"+processInstanceId);
				govMyAttentionDao.cancelAttention(processInstanceId);
				// 删除流程实例
				Map<String, String> params = new HashMap<String, String>();
	            params.put("userId", user.getUserId());
	            params.put("corpId", corpId);
	            params.put("processInstanceId", processInstanceId);
	            //逻辑删除流程实例，改变流程状态
	    	    bpmApiService.hideProcessInstance(params,user.getJwtToken());
	    	    //删除全文检索
				boolean openFlag = goaCommonUtil.judgeSearchServerOpen(corpId,token);
				if (openFlag) {
					govFullSearchService.deleteFullSerchByPage(user, ids);
				}
			}
			return OperationResult.buildSuccessResult("删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("删除失败"+e);
			return OperationResult.buildFailureResult("删除失败");
		}
	}


	/**
	 * @name: releaseBizCode
	 * @description: 释放流水号
	 * @param user
	 * @param dataId
	 * @param serialNumber
	 * @return: void
	 * @date: 2021/4/20 16:17
	 * @auther: fsx
	 *
	 */
	public void releaseBizCode(WebUser user,String dataId, String serialNumber, String bizId, String bizShowValue) {
		if (StringUtils.isNotEmpty(serialNumber)){
			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put("bizCode",serialNumber);
			paramMap.put("dataId",dataId);
			paramMap.put("id",bizId);
			paramMap.put("showValue",bizShowValue);
			org.ezplatform.util.RestClient restClient = new org.ezplatform.util.RestClient(true);
			bizcodeApiService.releaseBizCode(paramMap,user.getJwtToken());
		}
	}


	/**
	 * 更新发文字号的中的办理状态
	 * @param fileNoSee
	 * @param string
	 */
	public void updateFileNoStatus(String fileNoSee, String string) {
		// TODO Auto-generated method stub

	}

	/**
	 * 办件量统计查询   
	 * @Title: getHandlePage
	 * @param pageable
	 * @param corpId
	 * @param orgName
	 * @param userName
	 * @param startTime
	 * @param endTime
	 * @author xuwl
	 * @date 2019-12-04 10:09:50 AM 
	 */
	public Page<Map> getHandlePage(Pageable pageable, String corpId, String orgName, String userName, String startTime, String endTime) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		//boolean flag = GlobalConstant.isABase();
		StringBuffer sql = new StringBuffer();
		/*sql.append("select temp.* from (");
		sql.append("select t.ext_startuserid userid,u.user_name username,g2.org_name orgname,count(1) dealfiletotal,  ");
		sql.append("sum(case when t.end_time_ is null then 1 else 0 end) dealingcount, ");
		sql.append("sum(case when t.end_time_ is not null then 1 else 0 end) dealedcount, ");
		sql.append("g2.org_type,g2.sort_no,g2.id as gid ");
		sql.append("from act_hi_procinst t ");
		sql.append("left join sys_user u on u.id = t.ext_startuserid ");
		sql.append("left join sys_org g on g.id = t.ext_startusergroupid ");
		sql.append("left join sys_org g2 on g2.id = u.org_id ");
		sql.append("left join act_ru_variable var on var.PROC_INST_ID_ = t.id_ and var.name_ = 'ext_indraft' ");
        sql.append(" LEFT JOIN goa_doc_delrecord d ON t.BUSINESS_KEY_ = d.businesskey ");
		sql.append(" where t.business_key_ is not null and t.ext_module = 'goa_document' and t.DELETE_REASON_ is null and var.text_ is null ");
		sql.append(" AND g2.org_name is not null ");
        sql.append(" AND d.id is null ");*/

        sql.append(" SELECT t_user.id AS userid, t_user.user_name AS username, ");
        sql.append(" t_org.org_name AS orgname, COUNT(1) AS dealfiletotal, ");
        sql.append(" SUM(CASE WHEN t_proc.ext_processstatus = '1' THEN 1 ELSE 0 END) AS dealingcount, ");
        sql.append(" SUM(CASE WHEN t_proc.ext_processstatus IN ( '2', '3', '4') THEN 1 ELSE 0 END) AS dealedcount, ");
        sql.append(" t_org.org_type, t_org.sort_no, t_org.id AS gid ");
        sql.append(" FROM act_hi_procinst t_proc ");
        sql.append(" INNER JOIN sys_user t_user ON t_user.id = t_proc.ext_startuserid ");
        sql.append(" LEFT JOIN sys_org t_org ON t_org.id = t_user.org_id ");
        sql.append(" WHERE t_proc.ext_module = 'goa_document' ");
        sql.append(" AND t_proc.ext_processstatus IN ('1', '2', '3', '4') ");
        sql.append(" AND t_org.org_name IS NOT NULL ");
        sql.append(" AND NOT EXISTS (SELECT 1 FROM goa_doc_delrecord d WHERE t_proc.business_key_ = d.businesskey) ");


		if(StringUtils.isNotBlank(orgName)) {
			sql.append(" and t_org.org_name like :orgName ");
			paramMap.put("orgName", "%"+orgName+"%");
		}
		if(StringUtils.isNotBlank(userName)) {
			sql.append(" and t_proc.ext_startusername like :userName ");
			paramMap.put("userName", "%"+userName+"%");
		}
		if(StringUtils.isNotBlank(startTime)) {
			sql.append(" and t_proc.start_time_ >= :startTime ");
			paramMap.put("startTime", Timestamp.valueOf(startTime+" 00:00:00"));
		}
		if(StringUtils.isNotBlank(endTime)) {
			sql.append(" and t_proc.start_time_ <= :endTime ");
			paramMap.put("endTime", Timestamp.valueOf(endTime+" 23:59:59"));
		}
		/*****************添加权限begin by xuwenl***************/
		WebUser user = WebUtils.getCurrentUser();
		String permission = cmpPermissionService.getBusinessScopeSql("t_user", user, RightConstant.DOCUMENT_ANALYSIS_VIEW);
		permission = permission.replaceAll("createdOrg", "org_id");
		permission = permission.replaceAll("createdBy", "id");
		sql.append(permission);
		/*****************添加权限end by xuwenl***************/
		/*sql.append(" group by u.user_name,t.ext_startuserid,g2.org_name,g2.org_type,g2.sort_no,g2.id ");
		sql.append(" ) temp ");
		sql.append(" order by temp.org_type asc,temp.sort_no asc,temp.gid asc ");*/
        sql.append(" GROUP BY t_user.user_name,t_user.id,t_org.org_name,t_org.org_type,t_org.sort_no,t_org.id ");
        sql.append(" ORDER BY t_org.org_type ASC, t_org.sort_no ASC, t_org.id ASC ");
		return super.findByPageNativeSQL(pageable, sql.toString(), paramMap);
	}


	/**
	 * 办件量统计下钻流程数据   
	 * @Title: getHandleInfoPage
	 * @param pageable
	 * @param status
	 * @param userId
	 * @param startName
	 * @author xuwl
	 * @date 2019-12-04 11:35:10 AM 
	 */
	public Page<Map> getHandleInfoPage(Pageable pageable, String status, String userId, String startName, String startTime, String endTime, String psStartTime, String psEndTime) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		StringBuffer sql = new StringBuffer();
		/*if("1".equals(status)) {
			sql.append("select bb.* from (select DISTINCT t.id_, '办理中' as curStepName,t.ext_category category,t.BUSINESS_KEY_ businessKey,t.ext_title title,t.ext_startusername startUserName,g.org_name startUserGroupName,t.start_time_ createTime ");
			sql.append("from act_hi_procinst t ");
			sql.append(" LEFT JOIN act_hi_taskinst p ON p.proc_inst_id_ = t.id_ ");
			sql.append("left join sys_user u2 on u2.id = t.ext_startuserid ");
			sql.append("left join sys_org g on g.id = t.ext_startusergroupid ");
			sql.append("left join act_ru_variable var on var.PROC_INST_ID_ = t.id_ and var.name_ = 'ext_indraft' ");
			sql.append(" LEFT JOIN goa_doc_delrecord d ON t.BUSINESS_KEY_ = d.businesskey ");
			sql.append("where t.business_key_ is not null and t.ext_module = 'goa_document' AND t.end_time_ is null and t.DELETE_REASON_ is null and var.text_ is null ");
			sql.append(" AND d.id is null ");
		}else {
			sql.append("select bb.* from (select t.ext_category category,t.BUSINESS_KEY_ businessKey,t.ext_title title,t.ext_startusername startUserName,g.org_name startUserGroupName,t.start_time_ createTime,'已办结' curStepName ");
			sql.append("from act_hi_procinst t ");
			sql.append(" LEFT JOIN act_hi_taskinst p ON p.proc_inst_id_ = t.id_ ");
			sql.append("left join act_ru_variable var on var.PROC_INST_ID_ = t.id_ and var.name_ = 'ext_indraft' ");
			sql.append("left join sys_user u2 on u2.id = t.ext_startuserid ");
			sql.append("left join sys_org g on g.id = t.ext_startusergroupid ");
            sql.append(" LEFT JOIN goa_doc_delrecord d ON t.BUSINESS_KEY_ = d.businesskey ");
			sql.append("where t.business_key_ is not null and t.ext_module = 'goa_document' and t.end_time_ is not null and t.DELETE_REASON_ is null and var.text_ is null ");
            sql.append(" AND d.id is null ");
		}*/

		if("1".equals(status)) {
			sql.append(" select t_proc.id_, '办理中' as curStepName,t_proc.ext_category category,t_proc.BUSINESS_KEY_ businessKey,t_proc.ext_title title,t_proc.ext_startusername startUserName,t_org.org_name startUserGroupName,t_proc.start_time_ createTime ");
		}else{
			sql.append(" select t_proc.ext_category category,t_proc.BUSINESS_KEY_ businessKey,t_proc.ext_title title,t_proc.ext_startusername startUserName,t_org.org_name startUserGroupName,t_proc.start_time_ createTime,'已办结' curStepName ");
		}
		sql.append(" FROM act_hi_procinst t_proc ");
		sql.append(" INNER JOIN sys_user t_user ON t_user.id = t_proc.ext_startuserid ");
		sql.append(" LEFT JOIN sys_org t_org ON t_org.id = t_user.org_id ");
		sql.append(" WHERE t_proc.ext_module = 'goa_document' ");
		if("1".equals(status)) {
			sql.append(" AND t_proc.ext_processstatus = '1' ");
		}else{
			sql.append(" AND t_proc.ext_processstatus IN ( '2', '3', '4') ");
		}
		sql.append(" AND t_org.org_name IS NOT NULL ");
		sql.append(" AND NOT EXISTS (SELECT 1 FROM goa_doc_delrecord d WHERE t_proc.business_key_ = d.businesskey) ");

		if(StringUtils.isNotBlank(userId)) {
			sql.append(" and t_proc.ext_startuserId = :userId ");
			paramMap.put("userId", userId);
		}
		if("1".equals(status) && StringUtils.isNotBlank(startName)) {
			sql.append(" and t_proc.ext_startusername like :startName ");
			paramMap.put("startName", "%"+startName+"%");
		}
        if (StringUtils.isNotBlank(startTime)) {
            sql.append(" and t_proc.start_time_ >= :startTime ");
            paramMap.put("startTime", Timestamp.valueOf(startTime + " 00:00:00"));

        }
        if (StringUtils.isNotBlank(endTime)) {
            sql.append(" and t_proc.start_time_ <= :endTime ");
            paramMap.put("endTime", Timestamp.valueOf(endTime + " 23:59:59"));
        }
		if (StringUtils.isNotBlank(psStartTime)) {
			sql.append(" and t_proc.CLAIM_TIME_ >= :psStartTime ");
			paramMap.put("psStartTime", Timestamp.valueOf(psStartTime + " 00:00:00"));
		}
		if (StringUtils.isNotBlank(psEndTime)) {
			sql.append(" and t_proc.CLAIM_TIME_ <= :psEndTime ");
			paramMap.put("psEndTime", Timestamp.valueOf(psEndTime + " 23:59:59"));
		}
		sql.append(" ORDER BY t_proc.start_time_ desc ");
		return super.findByPageNativeSQL(pageable, sql.toString(), paramMap);
	}


	/**
	 * 领导文件统计   
	 * @Title: getLeaderHandlePage
	 * @param pageable
	 * @param userName  姓名
	 * @param orgName   所属单位
	 * @param startTime 发起日期开始
	 * @param endTime   发起日期结束
	 * @param psStartTime  批示日期开始
	 * @param psEndTime    批示日期结束
	 * @author xuwl
	 * @date 2019-12-04 3:09:51 PM 
	 */
    public Page<Map> getLeaderHandlePage(Pageable pageable, String userName, String orgName, String startTime, String endTime, String psStartTime, String psEndTime, List<PropertyFilter> buildFilters) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        StringBuffer sql = new StringBuffer();
//        sql.append("select aa.assignee_ userId,aa.user_name userName,aa.org_name orgName,count(1) dealfileTotal, ");
//        sql.append("sum(case when aa.end_time_ is null then 1 else 0 end) dealingCount, ");
//        sql.append("sum(case when aa.end_time_ is not null then 1 else 0 end) dealedCount,aa.gSort_no, aa.gCreatedDate,aa.USort_no,aa.uCreatedDate ");
//        sql.append("from ( ");
//        sql.append("select DISTINCT t.id_, u.user_name,g.org_name,t.end_time_,a.assignee_,g.sort_no gSort_no,u.sort_no USort_no,g.createdDate gCreatedDate,u.createdDate uCreatedDate from act_hi_taskinst a ");
//        sql.append("left join act_hi_procinst t on a.proc_inst_id_ = t.id_ and a.END_TIME_ is not null ");
//        sql.append("left join sys_user u on u.id = a.assignee_ ");
//        sql.append("left join sys_org g on g.id = u.org_id ");
//        sql.append("where t.business_key_ is not null and t.ext_module = 'goa_document' and ((t.delete_reason_ != '取消' and t.delete_reason_ != '作废') or t.delete_reason_ is null) ");
//        sql.append(" AND a.assignee_ in (SELECT l.leader_id FROM bpm_process_leader_setting l) ");

        sql.append(" select aa.assignee_ userId,aa.user_name userName,aa.org_name orgName,count(1) dealfileTotal, ");
        sql.append(" sum(case when aa.end_time_ is null then 1 else 0 end) dealingCount, ");
        sql.append(" sum(case when aa.end_time_ is not null then 1 else 0 end) dealedCount,aa.gSort_no, aa.gCreatedDate,aa.USort_no,aa.uCreatedDate ");
        sql.append(" from ( ");
        sql.append(" SELECT t.ASSIGNEE_,t.END_TIME_,u.user_name,u.sort_no USort_no,u.createdDate uCreatedDate,g.org_name,g.sort_no gSort_no,g.createdDate gCreatedDate ");
        sql.append(" FROM  ");
		sql.append("(( " +
				" SELECT " +
				" a.proc_inst_id_, " +
				" a.END_TIME_,  " +
				"a.assignee_ " +
				"FROM " +
				"act_hi_taskinst a " +
				"WHERE " +
				"a.END_TIME_ IS  NULL " +
				"GROUP BY a.proc_inst_id_,a.END_TIME_,a.assignee_) UNION ( " +
				"select " +
				"a.proc_inst_id_, " +
				"a.END_TIME_, " +
				"a.assignee_ FROM act_hi_taskinst a, " +
				"( " +
				"select " +
				"t.proc_inst_id_, " +
				"t.assignee_, " +
				"max(t.END_TIME_) as END_TIME_ " +
				"from " +
				"act_hi_taskinst t " +
				"left join act_hi_procinst p on " +
				"t.proc_inst_id_ = p.id_ where t.END_TIME_ is not null " +
				"group by " +
				"t.proc_inst_id_, " +
				"t.assignee_ ) b " +
				"where " +
				"a.proc_inst_id_ = b.proc_inst_id_ " +
				"and a.END_TIME_ = b.END_TIME_) ) t ");
        sql.append(" LEFT JOIN act_hi_procinst p ON t.proc_inst_id_ = p.id_ ");
        sql.append(" LEFT JOIN sys_user u ON u.id = t.assignee_ ");
        sql.append(" LEFT JOIN sys_org g ON g.id = u.org_id  ");
        sql.append(" WHERE 1=1 AND p.ext_module = 'goa_document' ");
        sql.append(" AND (( p.delete_reason_ != '取消' AND p.delete_reason_ != '作废' ) OR p.delete_reason_ IS NULL ) ");
        sql.append(" AND t.assignee_ in (SELECT l.leader_id FROM bpm_process_leader_setting l) ");
        if (StringUtils.isNotBlank(orgName)) {
            sql.append(" and g.org_name like :orgName ");
            paramMap.put("orgName", "%" + orgName + "%");
        }
        if (StringUtils.isNotBlank(userName)) {
            sql.append(" and u.user_name like :userName ");
            paramMap.put("userName", "%" + userName + "%");
        }
        if (StringUtils.isNotBlank(startTime)) {
            sql.append(" and p.start_time_ >= :startTime ");
            paramMap.put("startTime", Timestamp.valueOf(startTime + " 00:00:00"));
        }
        if (StringUtils.isNotBlank(endTime)) {
            sql.append(" and p.start_time_ <= :endTime ");
            paramMap.put("endTime", Timestamp.valueOf(endTime + " 23:59:59"));
        }
        if (StringUtils.isNotBlank(psStartTime)) {
            sql.append(" and t.END_TIME_ >= :psStartTime ");
            paramMap.put("psStartTime", Timestamp.valueOf(psStartTime + " 00:00:00"));
        }
        if (StringUtils.isNotBlank(psEndTime)) {
            sql.append(" and t.END_TIME_ <= :psEndTime ");
            paramMap.put("psEndTime", Timestamp.valueOf(psEndTime + " 23:59:59"));
        }

        /*****************添加权限end by xuwenl***************/
        sql.append(" ) aa ");
        sql.append(" group by aa.assignee_,aa.user_name,aa.org_name,aa.gSort_no, aa.gCreatedDate,aa.USort_no,aa.uCreatedDate ");
        String sqlStr = PropertyFilter.getSqlByFilterAndPageable("", sql.toString(), " aa.gSort_no asc, aa.gCreatedDate desc,aa.USort_no asc,aa.uCreatedDate desc ", buildFilters, pageable);
        return super.findByPageNativeSQL(pageable, sqlStr, paramMap);
    }


	/**
	 * @Title: getLeaderHandleInfoPage
	 * @Description: TODO
	 * @param pageable
	 * @param status
	 * @param psEndTime
	 * @param startName
	 * @return
	 * @author xuwl
	 * @date 2019-12-04 4:05:05 PM 
	 */
	public Page<Map> getLeaderHandleInfoPage(Pageable pageable, String status, String userId, String startName, String startTime, String endTime, String psStartTime, String psEndTime) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		StringBuffer sql = new StringBuffer();
//		sql.append("select bb.* from (select DISTINCT t.BUSINESS_KEY_ businessKey,u.user_name as curUserName,t.ext_category category,t.ext_title title,t.id_, t.ext_startusername startUserName,g.org_name startUserGroupName,t.start_time_ createTime ");
//		sql.append(" ,(case when a.name_ is not null then '办理中' else '已办结' end) curStepName ");//删去,c.text_ content
//		sql.append("from act_hi_procinst t ");
//		sql.append("left join act_hi_taskinst a on a.proc_inst_id_ = t.id_ and a.END_TIME_ is null ");
//		sql.append("left join sys_user u on u.id = a.assignee_ ");
//		sql.append("left join sys_user u2 on u2.id = t.ext_startuserid ");
//		sql.append("left join sys_org g on g.id = t.ext_startusergroupid  ");
//		sql.append("where t.id_ in ( ");
//		sql.append("select DISTINCT tt.id_ from act_hi_procinst tt ");
//		sql.append("left join act_hi_taskinst aa on aa.proc_inst_id_ = tt.id_ and aa.END_TIME_ is not null ");
//		if("1".equals(status)) {
//			sql.append("where tt.business_key_ is not null and tt.ext_module = 'goa_document' and t.END_TIME_ is null ");
//		}else {
//			sql.append("where tt.business_key_ is not null and tt.ext_module = 'goa_document' and t.END_TIME_ is not null ");
//		}
//		if(StringUtils.isNotBlank(userId)) {
//			sql.append(" and aa.assignee_ = :userId ");
//			paramMap.put("userId", userId);
//		}
//		sql.append(") and ((t.delete_reason_ != '取消' and t.delete_reason_ != '作废') or t.delete_reason_ is null) ");

        sql.append(" SELECT p.BUSINESS_KEY_ businessKey,u.user_name AS curUserName,p.ext_category category,p.ext_title title,p.id_,p.ext_startusername startUserName, ");
        sql.append(" g.org_name startUserGroupName,p.start_time_ createTime,t.END_TIME_ psTime,(CASE WHEN t.END_TIME_ IS NULL THEN '办理中' ELSE '已办结' END ) curStepName ");
        sql.append(" FROM  " );
		if("1".equals(status)){
			sql.append(" (" +
					"SELECT " +
					"a.proc_inst_id_," +
					"a.END_TIME_," +
					"a.assignee_ " +
					"FROM " +
					"act_hi_taskinst a " +
					"WHERE " +
					"a.END_TIME_ IS  NULL " +
					"AND a.assignee_ = :userId " +
					"GROUP BY a.proc_inst_id_,a.END_TIME_,a.assignee_) t  " );
		}else {
			sql.append(" (" +
					"SELECT " +
					"a.proc_inst_id_," +
					"a.END_TIME_," +
					"a.assignee_ " +
					"FROM " +
					"act_hi_taskinst a," +
					"(" +
					"SELECT " +
					"t.proc_inst_id_," +
					"t.assignee_," +
					"max(t.END_TIME_) AS END_TIME_ " +
					"FROM " +
					"act_hi_taskinst t " +
					"LEFT JOIN act_hi_procinst p ON " +
					"t.proc_inst_id_ = p.id_ " +
					"WHERE " +
					"t.END_TIME_ IS NOT NULL " +
					"AND t.assignee_ = :userId " +
					" GROUP BY " +
					" t.proc_inst_id_,t.assignee_ ) b " +
					"WHERE " +
					"a.proc_inst_id_ = b.proc_inst_id_ " +
					"AND a.END_TIME_ = b.END_TIME_) t  " );
		}
        sql.append(" LEFT JOIN act_hi_procinst p ON t.proc_inst_id_ = p.id_ ");
        sql.append(" LEFT JOIN sys_user u ON u.id = t.assignee_ ");
        sql.append(" LEFT JOIN sys_org g ON g.id = u.org_id ");
        sql.append(" WHERE 1=1 AND p.ext_module = 'goa_document' ");
        sql.append(" AND (( p.delete_reason_ != '取消' AND p.delete_reason_ != '作废' ) OR p.delete_reason_ IS NULL ) ");
        if ("1".equals(status)) {
            sql.append(" AND t.END_TIME_ IS NULL ");
        } else {
            sql.append(" AND t.END_TIME_ IS NOT NULL ");
        }
        if (StringUtils.isNotBlank(userId)) {
            sql.append(" and t.assignee_ = :userId ");
            paramMap.put("userId", userId);
        }
		if(StringUtils.isNotBlank(startName)) {
			sql.append(" and p.ext_startusername like :startName ");
			paramMap.put("startName", "%"+startName+"%");
		}
		if(StringUtils.isNotBlank(startTime)) {
            sql.append(" and p.start_time_ >= :startTime ");
            	paramMap.put("startTime", Timestamp.valueOf(startTime+" 00:00:00"));
		}
		if(StringUtils.isNotBlank(endTime)) {
            sql.append(" and p.start_time_ <= :endTime ");
            	paramMap.put("endTime", Timestamp.valueOf(endTime+" 23:59:59"));
		}
		if(StringUtils.isNotBlank(psStartTime)) {
            sql.append(" and t.END_TIME_ >= :psStartTime ");
            	paramMap.put("psStartTime", Timestamp.valueOf(psStartTime+" 00:00:00"));
		}
		if(StringUtils.isNotBlank(psEndTime)) {
            sql.append(" and t.END_TIME_ <= :psEndTime ");
            	paramMap.put("psEndTime", Timestamp.valueOf(psEndTime+" 23:59:59"));
		}
		sql.append("order by t.END_TIME_ desc");
		return super.findByPageNativeSQL(pageable, sql.toString(), paramMap);
	}

	/**
	 * 通过枚举的id获取枚举的名称
	 * @param fileTypeId
	 * @return
	 */
	public String getFileTypeName(String fileTypeId) {
		String fileName = StringUtils.EMPTY;
		Map<String, Object> paramMap = new HashMap<String, Object>();
		StringBuffer sql = new StringBuffer();
		sql.append(" select name from sys_dict_detail aa where id=:id");
		paramMap.put("id", fileTypeId);
		List<Map> list = super.findByListNativeQuery(sql.toString(), "",paramMap);
		if(!list.isEmpty()) {
			fileName = (String) list.get(0).get("name");
		}
		return fileName;
	}

	/**
	  * 根据id查询公开属性name
	 * @param id
	 * @return
	 */
	public String getPublishattribute(String id) {
		Map<String,String> mapNew = new HashMap<String,String>();
		String name_ = StringUtils.EMPTY;
		Map<String,Object> map =  govSendFileDao.getPublishattribute(id);

			 for (String string : map.keySet()) {
		            mapNew.put(string, map.get(string).toString());
		        }
			 String name_1 =JSONObject.toJSONString(mapNew);

		return name_1;
	}


	/**
	 * 根据PROC_INST_ID_查询办理人
	 * @Title: getHandlePerson
	 * @param procInstId
	 * @author xuwl
	 * @date 2019-12-16 6:01:58 PM 
	 */
	public List<Map> getHandlePerson(String procInstId) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("procInstId", procInstId);
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT u.user_name userName  from act_ru_execution ex ");
		sql.append("left join act_ru_variable var on ex.id_ = var.execution_id_ and ex.PROC_INST_ID_ = var.PROC_INST_ID_ and var.type_ = 'string' ");
		sql.append("left join sys_user u on var.text_ = u.id ");
		sql.append("where ex.PROC_INST_ID_ = :procInstId and ex.PARENT_ID_ is not null and ex.PARENT_ID_ != ex.PROC_INST_ID_ and ex.IS_ACTIVE_ = 1 ");
		return super.findByListNativeQuery(sql.toString(),"", paramMap);


	}


	/**
	 * 根据流程实例id获取公文的数据
	 * @param procInstId
	 * @return
	 */
	public  List<Map> getSendFileInfoByProcId(String procInstId) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("procInstId", procInstId);
		StringBuffer sql = new StringBuffer();
		sql.append("select gov.id,gov.file_no_see,gov.issued_number  from goa_doc_sendfile gov left join act_hi_procinst ahp on gov.id = ahp.business_key_  ");
		sql.append("where ahp.proc_inst_id_ = :procInstId");
		return super.findByListNativeQuery(sql.toString(),"", paramMap);
	}


	public int isKeepFileNo(String fileNoId, String useFileNo, String year, String corpId) {
		// 判断发文字号是否为共用文号 start
				List<String> fileNoIds = new ArrayList<>();
				if (StringUtils.isNotEmpty(fileNoId)) {
					GovSendFileNum sendFileNum = govSendFileNumService.findOne(fileNoId);
					String filenoGroupId = sendFileNum.getFilenoGroupId();
					if (StringUtils.isNotEmpty(filenoGroupId)) {
						DocSendFilegroup sendFilegroup = govSendGroupFileService.findOne(filenoGroupId);
						String filenoGroupAllid = sendFilegroup.getFilenoGroupAllid();
						if (StringUtils.isNotEmpty(filenoGroupAllid)) {
							String[] fileids = filenoGroupAllid.split(",");
							fileNoIds = Arrays.asList(fileids);
						}
					}
				}
				if (fileNoIds.size()>0) {
					return govSendFileNumDao.isKeepFileNos(fileNoIds, useFileNo, year, corpId);
				}else {
					return govSendFileNumDao.isKeepFileNo(fileNoId, useFileNo, year, corpId);
				}

	}

	/**
	 *
	 * 公文全文检索鉴权
	 * @Title: GovSendFileService
	 * @author: Fangsx
	 * @Date: 2020年4月14日 下午5:06:21 
	 * @param userId
	 * @param processInstanceId
	 * @return
	 * @throws
	 */
	public List<Map> checkUserTask(List<String> userId,List<String> processInstanceId) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("userId", userId);
		paramMap.put("processInstanceId", processInstanceId);
		StringBuffer sql = new StringBuffer();
		sql.append("select distinct b.BUSINESS_KEY_ as businessKey from act_hi_taskinst s left join act_hi_procinst b on s.PROC_INST_ID_ = b.PROC_INST_ID_  where s.ASSIGNEE_ in (:userId) and s.PROC_INST_ID_ in (:processInstanceId) ");
		List<Map> list = super.findByListNativeQuery(sql.toString(),"", paramMap);
		return list;
	}

	public Map<String, Object> getFlowInfo(String businessKey,String processInstanceId) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		Map<String, Object> map = new HashMap<String, Object>();
		paramMap.put("businessKey", businessKey);
		paramMap.put("processInstanceId", processInstanceId);
		StringBuffer sql = new StringBuffer();
		sql.append(" select t.id_ as id,p.key_ as processkey,t.form_key_ as formkey,p.category_ as category from act_hi_taskinst t left join act_re_procdef p on t.proc_def_id_ = p.id_ ");
		sql.append(" where proc_inst_id_ =:processInstanceId and t.ext_bussinesskey =:businessKey order by t.last_updated_time_ desc  ");
		List<Map> list = super.findByListNativeQuery(sql.toString(),"", paramMap);
		if (list != null && !list.isEmpty()) {
			map.put("processkey", StringUtils.null2String(list.get(0).get("processkey")));
			map.put("formkey", StringUtils.null2String(list.get(0).get("formkey")));
			map.put("category", StringUtils.null2String(list.get(0).get("category")));
			map.put("processkey", StringUtils.null2String(list.get(0).get("processkey")));
			map.put("value", StringUtils.null2String(list.get(0).get("id")));
			return map;
		}
		return null;
	}

	public Map getFormDataIdByProTaskId(String processInstanceId, String taskId) {
		String sql = "SELECT p.BUSINESS_KEY_ dataId,t.FORM_KEY_ formId FROM act_hi_procinst p INNER JOIN act_hi_taskinst t ON p.PROC_INST_ID_=t.PROC_INST_ID_ ";
		sql = sql + "WHERE p.PROC_INST_ID_=:processInstanceId ";
		Map paramMap = new HashMap();
		paramMap.put("processInstanceId", processInstanceId);
		if (StringUtils.isNotBlank(taskId)) {
			sql = sql + " AND t.ID_=:taskId ";
			paramMap.put("taskId", taskId);
		}
		sql = sql + " GROUP BY p.BUSINESS_KEY_,t.FORM_KEY_ ";
		List list = super.findByListNativeQuery(sql, "", paramMap);
		if ((null != list) && (list.size() > 0)) {
			return (Map) list.get(0);
		}
		return null;
	}

	public String getFormkeyByProTaskId(String taskId) {
	    String sql = "SELECT FORM_KEY_ formKey FROM act_hi_taskinst  WHERE ID_=:taskId ";
	    Map paramMap = new HashMap();
	    paramMap.put("taskId", taskId);
	    List list = super.findByListNativeQuery(sql, "", paramMap);
	    if ((null != list) && (list.size() > 0)) {
	      if (null == ((Map)list.get(0)).get("formKey")) {
	        return null;
	      }
	      return ((Map)list.get(0)).get("formKey").toString();
	    }

	    return null;
   }

	public List<Map<String, String>> getLinkageFieldsMap(String formId){
		WebUser user = WebUtils.getCurrentUser();
		Map hm = new HashMap();
		hm.put("formId", formId);
		hm.put("corpId", user.getCorpId());
		org.ezplatform.util.RestClient restClient = new org.ezplatform.util.RestClient(true);
		try {
			String json = formApiService.getLinkageFieldsMap(hm,user.getJwtToken());
			Map map = JsonUtils.readValue(json);
			if ("success".equals(map.get("type").toString())) {
				List list = (List)map.get("data");
				return list;
			}
		} catch (Exception e) {
			this.logger.error("获取表单关联信息失败", e);
			return null;
		}
		return null;
	}

	public Map<String, Object> getLinkFieldValueMap(String triggerFormFields, String formId, String conditionArrayJSON) {
		WebUser user = WebUtils.getCurrentUser();
		Map hm = new HashMap();
		hm.put("corpId", user.getCorpId());
		hm.put("formId", formId);
		hm.put("triggerFormFields", triggerFormFields);
		hm.put("conditionArrayJSON", conditionArrayJSON);
		try {
			String json = formApiService.getLinkageFieldsMap(hm,user.getJwtToken());
			Map map = JsonUtils.readValue(json);
			if ("success".equals(map.get("type").toString())) {
				Map returnMap = (Map)map.get("data");
				return returnMap;
			}
		} catch (Exception e) {
			return null;
		}
		return null;
	}

	public boolean isFocusDoc(String userId, String processId) {
		List list = new ArrayList();
		StringBuffer sql = new StringBuffer();
		sql.append(
				" select follow_process_id from bpm_process_followed where user_id = :userId and follow_process_id = :processId and  module = 'document' ");

		Map paramMap = new HashMap();
		paramMap.put("userId", userId);
		paramMap.put("processId", processId);
		List resultList = super.findByListNativeQuery(sql.toString(), "", paramMap);

		boolean res = false;
		if ((resultList != null) && (resultList.size() > 0)) {
			res = true;
		}
		return res;
	}

	public String getTitleByProInsId(String proId) {
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT t.ext_title title FROM act_hi_procinst t ");
		sb.append("WHERE t.PROC_INST_ID_ =:proId ");
		Map paramMap = new HashMap();
		paramMap.put("proId", proId);
		List list = super.findByListNativeQuery(sb.toString(), "", paramMap);
		if ((null != list) && (list.size() > 0)) {
			return ((Map) list.get(0)).get("title") + "";
		}
		return null;
	}

	/**
	 *
	 * @param businessKey
	 * @param corpId
	 * @return
	 */
	public boolean checkIsCancel(String businessKey, String corpId) {
		boolean res = false;
		StringBuffer sb = new StringBuffer();
		sb.append(" select EXT_PROCESSSTATUS as status from ACT_HI_PROCINST where BUSINESS_KEY_  =:businessKey");
		/*
		sb.append(" SELECT DISTINCT RES.END_TIME_ as endTime,RES.DELETE_REASON_ as reason ");
		sb.append(" FROM ACT_HI_PROCINST RES ");
		sb.append(" LEFT OUTER JOIN ACT_RE_PROCDEF DEF ON RES.PROC_DEF_ID_ = DEF.ID_ ");
		sb.append(
				" LEFT OUTER JOIN act_hi_varinst VAR1 ON VAR1.PROC_INST_ID_ = RES.ID_ AND VAR1.NAME_ = 'ext_indraft' ");

		sb.append(" WHERE 1 = 1  ");
		sb.append(" AND RES.BUSINESS_KEY_ IS NOT NULL ");
		sb.append(" AND RES.TENANT_ID_ =:corpId ");
		sb.append(" and RES.BUSINESS_KEY_  =:businessKey ");*/
		Map paramMap = new HashMap();
		//paramMap.put("corpId", corpId);
		paramMap.put("businessKey", businessKey);
		List list = super.findByListNativeQuery(sb.toString(), "", paramMap);
		if (list.size() > 0) {
			/*Map map = (Map) list.get(0);
			String reason = StringUtils.null2String(map.get("reason"));
			if (("取消".equals(reason)) || ("作废".equals(reason))) {
				res = true;
			}*/
			Map map = (Map) list.get(0);
			String status = StringUtils.null2String(map.get("status"));
			if (("3".equals(status)) || ("4".equals(status))) {
				res = true;
			}
		}
		return res;
	}

	public Map getDbList(String userId, String limit) {
		Map resultMap = new HashMap();
		StringBuffer sb = new StringBuffer();
		StringBuffer sb1 = new StringBuffer();
	    sb.append(" SELECT  DISTINCT RES.*, RES.create_time_ AS createTime ,RES.proc_inst_id_ as processInstanceId, HIP.EXT_TITLE AS title " +
	    		"          ,HIP.BUSINESS_KEY_ AS businessKey " +
	    		"          ,HIP.EXT_PREWARNINGDATE AS EXT_PROCESSPREWARNINGDATE " +
	    		"          ,HIP.EXT_WARNINGDATE AS EXT_PROCESSWARNINGDATE " +
	    		"          ,HIP.EXT_STARTUSERGROUPID AS EXT_STARTUSERGROUPID " +
	    		"          ,HIP.EXT_STARTUSERID AS EXT_STARTUSERID " +
	    		"          ,HIP.EXT_PROCESSCODE AS EXT_PROCESSDEFINITIONKEY " +
	    		" FROM   ACT_RU_TASK RES   INNER JOIN ACT_HI_PROCINST HIP ON HIP.ID_ = RES.PROC_INST_ID_  " +
	    		" LEFT JOIN ACT_RU_IDENTITYLINK I ON I.TASK_ID_ = RES.ID_ " +
	    		" WHERE RES.EXT_MODULE = 'goa_document'" +
	    		" AND RES.EXT_HIDE_UNDOLIST IS NULL " +
	    		" AND RES.TENANT_ID_ = 0" +
	    		" AND ( (  RES.ASSIGNEE_ =:userId ) " +
	    		" OR ( RES.ASSIGNEE_ IS NULL AND I.TYPE_ = 'candidate' AND (I.USER_ID_ = :userId)" +
	    		" ))" +
	    		"and rownum >0 and rownum < 10 ORDER BY RES.create_time_ DESC " );
	    sb1.append(" SELECT count(*) "+
	    		" FROM   ACT_RU_TASK RES   INNER JOIN ACT_HI_PROCINST HIP ON HIP.ID_ = RES.PROC_INST_ID_  " +
	    		" LEFT JOIN ACT_RU_IDENTITYLINK I ON I.TASK_ID_ = RES.ID_ " +
	    		" WHERE RES.EXT_MODULE = 'goa_document'" +
	    		" AND RES.EXT_HIDE_UNDOLIST IS NULL " +
	    		" AND RES.TENANT_ID_ = 0" +
	    		" AND ( (  RES.ASSIGNEE_ =:userId ) " +
	    		" OR ( RES.ASSIGNEE_ IS NULL AND I.TYPE_ = 'candidate' AND (I.USER_ID_ = :userId)" +
	    		" ))" +
	    		" ORDER BY RES.create_time_ DESC " );
	    Map paramMap = new HashMap();
	    paramMap.put("userId", userId);
	    List list = this.findByListNativeQuery(sb.toString(), "", paramMap);
	    List list1 = this.findByListNativeQuery(sb.toString(), "", paramMap);
	    int total = 0;
	    if((null != list1) && (list1.size() > 0)) {
	    	total = list1.size();
	    }
	    resultMap.put("list", list);
	    resultMap.put("total", total);
	    return resultMap;
	}


	/**
	 * 公文查询是需要的参数
	 * @param id
	 * @return
	 */
	public Map<String, String> getParamsBySearch(String id) {
	   	Map<String,String> resultMap = new HashMap<String,String>();
    	Map<String, Object> paramMap = new HashMap<String, Object>();
		StringBuffer sql = new StringBuffer();
		sql.append(" select  aph.business_key_ ,art.proc_def_id_,art.form_key_,aph.proc_inst_id_,art.id_ ");
		sql.append("  from ACT_HI_PROCINST aph left join  ACT_RU_TASK art  on  art.PROC_INST_ID_= aph.PROC_INST_ID_ ");
		sql.append(" where  aph.business_key_ = :id ");
		paramMap.put("id", id);
		List<Map> list = super.findByListNativeQuery(sql.toString(), "",paramMap);
		if(CollectionUtils.isNotEmpty(list)) {
			for(int i = 0; i < list.size(); i++) {
				String proc_def_id_ = (String) list.get(0).get("proc_def_id_");
				String form_key_=  (String) list.get(0).get("form_key_");
				resultMap.put("proc_def_id_",proc_def_id_);
				resultMap.put("form_key_",form_key_);
			}
		}
    	return resultMap;
	}

	/**
	 * 查询草稿箱数量
	 * @param userId
	 * @param corpId
	 * @param modules
	 * @return
	 */
	public String getDraftNum(String userId, String corpId, String modules) {
		String draftNum = "0";
		Map<String, Object> paramMap = new HashMap<String, Object>();
		String sql  ="select count(*) as draftnum from act_hi_procinst where EXT_MODULE = :modules and "
				+ "EXT_PROCESSSTATUS  = '0' and START_USER_ID_ = :userId and DELETE_REASON_ is  null ";
		paramMap.put("userId", userId);
		paramMap.put("modules", modules);
		List<Map> list = super.findByListNativeQuery(sql, "",paramMap);
		if(CollectionUtils.isNotEmpty(list)) {
			 draftNum = String.valueOf(list.get(0).get("draftnum"));
		}
    	return draftNum;
	}

	/**
	 * 查询公文已办数量
	 * @param userId
	 * @param corpId
	 * @param modules
	 * @return
	 */
	public String getDoneNum(String userId, String corpId, String modules) {
		String doneNum = "0";
		Map<String, Object> paramMap = new HashMap<String, Object>();
		//已办sql优化
		String sql  ="select count(distinct p.id_) donenum from act_hi_procinst p inner join act_hi_taskinst t " +
				"on p.id_=t.proc_inst_id_  where p.ext_module=:modules  and p.tenant_id_='0' " +
				"and ( t.EXT_HIDE_DONELIST is NULL or t.EXT_HIDE_DONELIST='0' ) " +
				"and (p.ext_processstatus='1' or p.ext_processstatus='2'or p.ext_processstatus='3' or p.ext_processstatus='4')" +
				" and t.END_TIME_ IS NOT NULL and t.assignee_=:userId ";
		paramMap.put("userId", userId);
		paramMap.put("modules", modules);
		List<Map> list = super.findByListNativeQuery(sql, "",paramMap);
		if(CollectionUtils.isNotEmpty(list)) {
			 doneNum = String.valueOf(list.get(0).get("donenum"));
		}
    	return doneNum;

	}

	/**
	 * 查询我的发起数量
	 * @param userId
	 * @param corpId
	 * @param modules
	 * @return
	 */
	public String getMyStartNum(String userId, String corpId, String modules) {
		String myStartNum = "0";
		Map<String, Object> paramMap = new HashMap<String, Object>();
		String sql  ="select count(*) as mystartnum from act_hi_procinst where EXT_MODULE = :modules and "
				+ " START_USER_ID_ = :userId  and ext_processstatus  in (1,2,3,4) ";
		paramMap.put("userId", userId);
		paramMap.put("modules", modules);
		List<Map> list = super.findByListNativeQuery(sql, "",paramMap);
		if(CollectionUtils.isNotEmpty(list)) {
			myStartNum = String.valueOf(list.get(0).get("mystartnum"));
		}
    	return myStartNum;
	}

	/**
	 * @name: getComListByProTaskType
	 * @description: 获取批示意见列表
	 * @param processInstanceId
	 * @param taskId
	 * @param commentType
	 * @param userId
	 * @return: java.util.List<java.util.Map>
	 * @date: 2021/3/17 15:24
	 * @auther: fsx
	 *
	*/
	public List<Map> getComListByProTaskType(String processInstanceId,String taskId,String commentType,String userId) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
        StringBuffer sql = new StringBuffer();
        sql.append(" SELECT b.id,b.content,b.field,b.type FROM bpm_process_comment b ");
        sql.append(" LEFT JOIN goa_doc_distribute_record r ON r.process_instance_id = b.processinstance_id ");
        sql.append(" LEFT JOIN goa_doc_distribute_user u ON u.dis_record_id = r.id ");
        sql.append(" WHERE b.processinstance_id = :processInstanceId ");
        sql.append(" AND b.signtype = :commentType AND b.task_id  =:taskId and b.user_id =:userId ");
        sql.append(" AND u.status = '0' ");
//		String sql  ="select id,content,field from  bpm_process_comment where processinstance_id = :processInstanceId and "
//				+ " signtype = :commentType  and task_id  =:taskId and user_id =:userId ";
		paramMap.put("userId", userId);
		paramMap.put("processInstanceId", processInstanceId);
		paramMap.put("taskId", taskId);
		paramMap.put("commentType", commentType);
		List<Map> list = super.findByListNativeQuery(sql.toString(), "",paramMap);
    	return list;
	}

	/**
	 * @name: getComListByProcInsId
	 * @description: 获取批示意见列表
	 * @param processInstanceId
	 * @return: java.util.List<java.util.Map>
	 * @date: 2021/3/17 15:23
	 * @auther: fsx
	 *
	*/
	public List<Map> getComListByProcInsId(String processInstanceId,String field) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		String sql  ="select id,content,field,user_name as userName from  bpm_process_comment where processinstance_id = :processInstanceId   ";
		paramMap.put("processInstanceId", processInstanceId);
		if (StringUtils.isNotEmpty(field)){
			sql += " and field = :field";
			paramMap.put("field", field);
		}
		sql += " order by createdDate desc ";
		List<Map> list = super.findByListNativeQuery(sql, "",paramMap);
		return list;
	}

	/**
	 * @name: saveTextHistory
	 * @description: 保存正文版本
	 * @param user
	 * @param businessKey
	 * @param taskId
	 * @param recordId
	 * @param rollFlag
	 * @return: void
	 * @date: 2021/5/25 16:56
	 * @auther: fsx
	 *
	 */
	public void saveTextHistory(WebUser user, String businessKey, String taskId, String recordId, String rollFlag,String stampedTransferSeal) {
		if (StringUtils.isNotEmpty(recordId) && StringUtils.isNotEmpty(businessKey)) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("recordId", recordId);
			map.put("corpId", user.getCorpId());
			String result = goldgridApiSevice.getDocumentFileMap(map,user.getJwtToken());
			if (StringUtils.isNoneBlank(result)) {
				JSONObject json = (JSONObject) JSONObject.parse(result);
				Object success = json.get("success");
				Object content = json.get("content");
				if (success != null && success.toString().equals("true")) {
					if (content != null) {
						JSONObject attachment = (JSONObject)content;
						if (attachment.get("attachment") !=null) {
							JSONObject val = (JSONObject)attachment.get("attachment");
							if (val.get("id") !=null && val.get("checksum") !=null) {
								String fileId = val.get("id").toString();
								String checksum = val.get("checksum").toString();
								String fileExt = val.get("fileExt").toString();
								Map saveHistoryFile = copyFileUtils.saveHistoryFile(fileId, checksum, "goa_doc_history",fileExt);
								List<GovDocFileEdition> listByTask = fileEditionService.getListByTask(businessKey, taskId,"1",user.getUserId());
								if (null == listByTask || listByTask.isEmpty()) {//当前环节保存过一次
									saveFileEdition(recordId, businessKey, taskId, user, saveHistoryFile,"1","0","0", "", "", "", "","0");
								}else {
									if (StringUtils.isNoneEmpty(rollFlag) && rollFlag.equals("1")) {//判断是否回退正文版本生成的新版本
										saveFileEdition(recordId, businessKey, taskId, user, saveHistoryFile,"1","0","0", "", "", "", "","0");
									}else {
										List<GovDocFileEdition> listByDoc = fileEditionService.getListByDoc(businessKey,"1");
										GovDocFileEdition govDocFileEdition = listByDoc.get(0);
										if (govDocFileEdition != null) {
											if (govDocFileEdition.getVersionName().equals(user.getUserId()) ) {
												attachmentUtilsService.delete(govDocFileEdition.getFileId(), govDocFileEdition.getChecksum(), user.getJwtToken());
												govDocFileEdition.setFileId(saveHistoryFile.get("id").toString());
												govDocFileEdition.setVersionTime(new Date());
												govDocFileEdition.setChecksum(saveHistoryFile.get("checksum").toString());
												fileEditionService.save(govDocFileEdition);
											}else {
												saveFileEdition(recordId, businessKey, taskId, user, saveHistoryFile,"1","0","0", "", "", "", "","0");
											}

										}
									}
								}
							}
						}
					}
				}
			}

		}
	}

	public void saveTextApproveHistory(WebUser user, String businessKey, String taskId, String recordId, String multipleSignApprove, String flag, String displayName,
									   String fileType, String parentProcessInstanceId, String newInstanceid, String processName,String stampedTransferSeal) {
		this.saveTextApproveHistory(user,  businessKey,  taskId,  recordId,  multipleSignApprove,  flag,  displayName,
				 fileType,  parentProcessInstanceId,  newInstanceid,  processName, stampedTransferSeal, "");

	}

	/**
	 * @param user
	 * @param businessKey
	 * @param taskId
	 * @param recordId
	 * @param multipleSignApprove
	 * @param parentProcessInstanceId
	 * @param newInstanceid
	 * @param processName
	 * @name: saveTextApproveHistory
	 * @description: 保存正文签批版本
	 * @return: void
	 * @date: 2021/5/25 16:56
	 * @auther: fsx
	 */
	public void saveTextApproveHistory(WebUser user, String businessKey, String taskId, String recordId, String multipleSignApprove, String flag, String displayName,
									   String fileType, String parentProcessInstanceId, String newInstanceid, String processName,String stampedTransferSeal,String modifiedAttachments) {
		if (StringUtils.isNotEmpty(recordId) && StringUtils.isNotEmpty(businessKey)) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("recordId", recordId);
			map.put("corpId", user.getCorpId());
			Map<String, Object> attachment = govDocAttachmentService.getFormatFileInfo(recordId);
			String rootProcessInstanceId = "";
			if (StringUtils.isEmpty(parentProcessInstanceId)){
				Map<String,String> parentMap = getParentProcessId(newInstanceid);
				if (parentMap != null && !parentMap.isEmpty()){
					parentProcessInstanceId = parentMap.get("parentProcessInstanceId");
					rootProcessInstanceId = parentMap.get("rootProcessInstanceId");
				}
			}
			logger.error("saveTextApproveHistory  attachment-------------------->"+attachment.toString());
			if (attachment != null) {
			    String isHidden = "0";
				String modified = "0";//是否有签批
				logger.error("saveTextApproveHistory  multipleSignApprove-------------------->"+multipleSignApprove);
				logger.error("saveTextApproveHistory  flag-------------------->"+flag);
				if("1".equals(multipleSignApprove) && (StringUtils.isBlank(flag) || "3".equals(flag) || "4".equals(flag))){
                    //多文件签批时,保存不显示签批文件记录,提交后才显示
                    isHidden = "1";
                }
				if (attachment.get("id") !=null && attachment.get("checksum") !=null) {

                    Map<String,Object> saveHistoryFile = attachment;
					logger.error("saveTextApproveHistory  saveHistoryFile-------------------->"+saveHistoryFile.toString());

					if(!"1".equals(multipleSignApprove)){
                        //同文件签批生成记录,复制一份版式文件
                        String fileId = StringUtils.null2String(attachment.get("id"));
						logger.error("===saveTextApproveHistory===modifiedAttachments:{}====fileId:{}====",modifiedAttachments,fileId);

						if(StringUtils.isNotBlank(modifiedAttachments)&&modifiedAttachments.indexOf(fileId)>-1){
							modified = "1";
						}

                        String checksum = StringUtils.null2String(attachment.get("checksum"));
                        String fileExt = StringUtils.null2String(attachment.get("file_ext"));
                        saveHistoryFile = copyFileUtils.saveHistoryFile(fileId, checksum, "goa_doc_history",fileExt, displayName);
						logger.error("saveTextApproveHistory  saveHistoryFile-------------------->"+saveHistoryFile.toString());
					}
					List<GovDocFileEdition> listByTask = fileEditionService.getListByTask(businessKey, taskId,fileType,user.getUserId());
					logger.error("saveTextApproveHistory  listByTask-------------------->"+listByTask.toString());

					if (null == listByTask || listByTask.isEmpty()) {
						saveFileEdition(recordId, businessKey, taskId, user, saveHistoryFile,fileType,isHidden,
								"0",parentProcessInstanceId,newInstanceid,processName,rootProcessInstanceId,stampedTransferSeal,modified);
					}else {
                        //当前环节保存过
						List<GovDocFileEdition> listByDoc = fileEditionService.getListByDoc(businessKey,fileType);
						GovDocFileEdition govDocFileEdition = listByDoc.get(0);
						logger.error("saveTextApproveHistory  govDocFileEdition-------------------->"+govDocFileEdition.toString());

						if (govDocFileEdition != null) {
							if (govDocFileEdition.getVersionName().equals(user.getUserId()) ) {
							    if(!"1".equals(multipleSignApprove)){
							        //同文件签批删除复制的文件
                                    attachmentUtilsService.delete(govDocFileEdition.getFileId(), govDocFileEdition.getChecksum(), user.getJwtToken());
                                }
								govDocFileEdition.setFileId(saveHistoryFile.get("id").toString());
								govDocFileEdition.setVersionTime(new Date());
								govDocFileEdition.setChecksum(saveHistoryFile.get("checksum").toString());
								govDocFileEdition.setIsHidden(isHidden);
								govDocFileEdition.setIsReview("0");
								govDocFileEdition.setIsSeal(stampedTransferSeal);//加盖分转章 1是 0否
								govDocFileEdition.setProcessName(processName);
								govDocFileEdition.setProcessId(newInstanceid);
								if (StringUtils.isNotEmpty(parentProcessInstanceId)){
									govDocFileEdition.setRootProcessId(rootProcessInstanceId);
									govDocFileEdition.setParentProcessId(parentProcessInstanceId);
								}else {
									govDocFileEdition.setRootProcessId(newInstanceid);
									govDocFileEdition.setParentProcessId(newInstanceid);
								}
								modified = "1".equals(modified)?modified:govDocFileEdition.getModified();
								if(StringUtils.isNotBlank(modified)){
									govDocFileEdition.setModified(modified);
								}
								fileEditionService.save(govDocFileEdition);
							}else {
								logger.error("saveTextApproveHistory  fileType-------------------->"+fileType);
								saveFileEdition(recordId, businessKey, taskId, user, saveHistoryFile,fileType,isHidden,
										"0", parentProcessInstanceId, newInstanceid, processName, rootProcessInstanceId,stampedTransferSeal,modified);
							}

						}
					}
				}
			}

		}
	}


	public Map<String,String> getParentProcessId(String processInstanceId){
		//logger.error("getParentProcessId--------进入------processInstanceId:{}",processInstanceId);
		Map<String,String> result = new HashMap();
		if(StringUtils.isBlank(processInstanceId)){
			return result;
		}
		Map sqlMap = new HashMap();
		StringBuffer sb = new StringBuffer();
		String parentProcessInstanceId = "";
		sb.append("select TEXT_ from act_hi_varinst where PROC_INST_ID_  = :processInstanceId and NAME_ = 'parentProcessInstanceId' ");
		sqlMap.put("processInstanceId", processInstanceId);
		List<Map> list = super.findByListNativeQuery(sb.toString(), "", sqlMap);
		if(list.size()>0){
			parentProcessInstanceId = StringUtils.null2String(list.get(0).get("TEXT_"));
			//如果只有一级的话，存储父级流程实例id
			result.put("parentProcessInstanceId",parentProcessInstanceId);
			result.put("rootProcessInstanceId",parentProcessInstanceId);
			//如果不止一级，需要查询顶级流程实例id
			if(StringUtils.isNotBlank(parentProcessInstanceId)){
				while (true){
					StringBuffer sb1 = new StringBuffer();
					Map sqlMap1 = new HashMap();
					sb1.append("select TEXT_ from act_hi_varinst where PROC_INST_ID_  = :processInstanceId and NAME_ = 'parentProcessInstanceId' ");
					sqlMap1.put("processInstanceId", parentProcessInstanceId);
					List<Map> list1 = super.findByListNativeQuery(sb1.toString(), "", sqlMap1);
					if(list1!=null&&list1.size()>0){
						String rootProcessInstanceId = StringUtils.null2String(list1.get(0).get("TEXT_"));
						result.put("rootProcessInstanceId",rootProcessInstanceId);
						parentProcessInstanceId = rootProcessInstanceId;
					}else{
						break;
					}
				}
			}
		}
		return result;
	}

	public void saveFileEdition(String recordId, String docId, String taskId, WebUser webUser, Map saveHistoryFile, String fileType, String isHidden, String isReview, String parentProcessInstanceId, String newInstanceid, String processName, String rootProcessInstanceId, String stampedTransferSeal) {
		this.saveFileEdition(recordId, docId, taskId, webUser, saveHistoryFile, fileType, isHidden, isReview, parentProcessInstanceId, newInstanceid, processName, rootProcessInstanceId, stampedTransferSeal, "");
	}


	/**
	 * @param recordId
	 * @param docId
	 * @param taskId
	 * @param webUser
	 * @param saveHistoryFile
	 * @param parentProcessInstanceId
	 * @param newInstanceid
	 * @param processName
	 * @param rootProcessInstanceId
	 * @name: saveFileEdition
	 * @description: 保存版本
	 * @return: void
	 * @date: 2021/5/25 16:55
	 * @auther: fsx
	 */
	public void saveFileEdition(String recordId, String docId, String taskId, WebUser webUser, Map saveHistoryFile, String fileType, String isHidden, String isReview, String parentProcessInstanceId, String newInstanceid, String processName, String rootProcessInstanceId,String stampedTransferSeal,String modified) {
		List<GovDocFileEdition> listByDoc = fileEditionService.getListByDoc(docId,fileType);
		logger.error("listByDoc---------------->"+listByDoc.size());
		logger.error("saveFileEdition isHidden---------------->"+isHidden);

		logger.error("listByDoc---------------->"+listByDoc.toString());
		if (listByDoc == null || listByDoc.isEmpty()) {//是否存在历史版本
			GovDocFileEdition docFileEdition = new GovDocFileEdition();
			docFileEdition.setFileId(saveHistoryFile.get("id").toString());
			docFileEdition.setFileType(fileType);
			docFileEdition.setGoaId(docId);
			docFileEdition.setRecordId(recordId);
			docFileEdition.setVersionName(webUser.getUserId());
			docFileEdition.setVersionTime(new Date());
			docFileEdition.setVersionUnit(webUser.getOrgId());
			docFileEdition.setTextVersion(1);
			docFileEdition.setTextVersionName("V"+ 1);
			docFileEdition.setChecksum(saveHistoryFile.get("checksum").toString());
			docFileEdition.setTaskId(taskId);
			if (StringUtils.isNotEmpty(taskId)){
				docFileEdition.setTaskName(fileEditionService.getTaskName(taskId));
			}
			docFileEdition.setIsHidden(isHidden);
			docFileEdition.setIsReview(isReview);
			docFileEdition.setIsSeal(stampedTransferSeal);
			docFileEdition.setProcessId(newInstanceid);
			docFileEdition.setProcessName(processName);
			if (StringUtils.isNotEmpty(parentProcessInstanceId)){
				docFileEdition.setRootProcessId(rootProcessInstanceId);
				docFileEdition.setParentProcessId(parentProcessInstanceId);
			}else {
				docFileEdition.setRootProcessId(newInstanceid);
				docFileEdition.setParentProcessId(newInstanceid);
			}

			if(StringUtils.isNotBlank(modified)){
				docFileEdition.setModified(modified);
			}
			fileEditionService.save(docFileEdition);
		}else {
			GovDocFileEdition govDocFileEdition = listByDoc.get(0);
			logger.error("govDocFileEdition---------------->"+govDocFileEdition.toString());

			if (govDocFileEdition != null) {
				GovDocFileEdition docFileEdition = new GovDocFileEdition();
				docFileEdition.setFileId(saveHistoryFile.get("id").toString());
				docFileEdition.setFileType(fileType);
				docFileEdition.setGoaId(docId);
				docFileEdition.setRecordId(recordId);
				docFileEdition.setVersionName(webUser.getUserId());
				docFileEdition.setVersionTime(new Date());
				docFileEdition.setVersionUnit(webUser.getOrgId());
				if("0".equals(isHidden)){
                    docFileEdition.setTextVersion(govDocFileEdition.getTextVersion()+1);
                    docFileEdition.setTextVersionName("V"+ (govDocFileEdition.getTextVersion()+1));
                }
				docFileEdition.setChecksum(saveHistoryFile.get("checksum").toString());
				docFileEdition.setTaskId(taskId);
				if (StringUtils.isNotEmpty(taskId)){
					docFileEdition.setTaskName(fileEditionService.getTaskName(taskId));
				}
                docFileEdition.setIsHidden(isHidden);
				docFileEdition.setIsReview(isReview);
				docFileEdition.setIsSeal(stampedTransferSeal);
				docFileEdition.setProcessId(newInstanceid);
				docFileEdition.setProcessName(processName);

				modified = "1".equals(modified)?modified:govDocFileEdition.getModified();
				if(StringUtils.isNotBlank(modified)){
					docFileEdition.setModified(modified);
				}

				if (StringUtils.isNotEmpty(parentProcessInstanceId)){
					docFileEdition.setRootProcessId(rootProcessInstanceId);
					docFileEdition.setParentProcessId(parentProcessInstanceId);
				}else {
					docFileEdition.setRootProcessId(newInstanceid);
					docFileEdition.setParentProcessId(newInstanceid);
				}
				fileEditionService.save(docFileEdition);
			}
		}
	}


	public String getRootProcessId(String processId) {
		WebUser user = WebUtils.getCurrentUser();
		String rootProcessId = "";
		if (StringUtils.isNotEmpty(processId)) {
			Map<String, String> paramMap =  new HashMap<>();
			paramMap.put("processInstanceId", processId);
			String data = restClient.get("/bpm/runtime/getRootProcInstId",user.getJwtToken(), paramMap);
			logger.error("bpm/runtime/getRootProcInstId res {}"+data);
			if (StringUtils.isNotEmpty(data)) {
				JSONObject jsonObject = JSONObject.parseObject(data);
				if (jsonObject.get("code").equals(200)) {
					rootProcessId = jsonObject.get("data").toString();
				}
			}
		}
		return rootProcessId;
	}


	public void updateAttachmentDocumentId(String type, String businessKey, String attachmentList, String initAttachmentList, String fileSecurityList, String permissionCode) {
		this.updateAttachmentDocumentId( type, businessKey, attachmentList,initAttachmentList, fileSecurityList, permissionCode,"","","");
	}

	/**
	 * @name: updateAttachmentDocumentId
	 * @description: 更新附件表主表id
	 * @param type
	 * @param businessKey
	 * @param attachmentList
	 * @param fileSecurityList
	 * @param permissionCode
	 * @return: void
	 * @date: 2021/5/25 17:22
	 * @auther: fsx
	 *
	 */
	public void updateAttachmentDocumentId(String type, String businessKey, String attachmentList, String initAttachmentList, String fileSecurityList, String permissionCode, String enableHandSignature,String taskId,String title) {
		logger.info("=======updateAttachmentDocumentId======attachmentList:{}====",attachmentList);
		//if(StringUtils.isEmpty(attachmentList) || "null".equals(attachmentList)) return;
		WebUser user = WebUtils.getCurrentUser();
		String userId = user.getUserId();
		//关联的附件表处理
		if(attachmentList!=null&&!"".equals(attachmentList)) {
			Map<String,String> securityMap = new HashMap<String,String>();
			List<Map<String,String>> securityList = goaCommonUtils.getEnumerationByCode("security_classificat");
			if(securityList!=null&&securityList.size()>0) {
				for(int i=0;i<securityList.size();i++) {
					Map<String,String> mapOne = securityList.get(i);
					if(StringUtils.isEmpty(securityMap.get(mapOne.get("id").toString()))) {
						securityMap.put(mapOne.get("id").toString(), mapOne.get("name").toString());
					}
				}
			}
			List<String> aList = new ArrayList<String>();
			String[] attachmentArr = attachmentList.split("\\|");
			for(int i=0;i<attachmentArr.length;i++) {
				aList.add(attachmentArr[i]);
			}

			//处理附件被删除问题 20250208 start
			List<String> initAList = new ArrayList<String>();
			if(initAttachmentList!=null&&!"".equals(initAttachmentList)) {
				String[] initAttachmentArr = initAttachmentList.split("\\|");
				for(int i=0;i<initAttachmentArr.length;i++) {
					initAList.add(initAttachmentArr[i]);
				}
			}
			//处理附件被删除问题 20250208 end
			List<GovDocAttachment> newList = new ArrayList<GovDocAttachment>();
			//修改记录
			//新增的记录 {id:[名字,来源,绑定的关联主表id]}
			Map<String,Object> addupdateRecord = new LinkedHashMap<String,Object>();
			//修改的记录  {id:[老密级,新密级,名字,来源,绑定的关联主表id]}
			Map<String,Object> updateupdateRecord = new HashMap<String,Object>();
			//删除的记录 {id:[名字,来源,绑定的关联主表id]}
			Map<String,Object> deleteupdateRecord = new LinkedHashMap<String,Object>();
			//新的关联主表的附件数据
			List<GovDocAttachment> list = govDocAttachmentDao.getAttachmentListByRealIds(aList);
			if(list!=null && !list.isEmpty()) {
				/*list = list.stream()
						.collect(Collectors.collectingAndThen(
								Collectors.toCollection(() ->
										new TreeSet<>(Comparator.comparing((o)-> o.getSysAttchmentId().toString()))), ArrayList::new));*/
                list = list.stream()
                        .sorted(Comparator.comparing(GovDocAttachment::getSortNo))
                        .collect(Collectors.toList()); // 默认就是ArrayList

				//准备删除不要关联的数据(主要因为自定义表单上传的附件删除只是隐藏域的数值的删除,
				//并没有对后台数据进行删除,所以在保存接口对于这块的数据进行删除
				//为什么没有对于数据进行实时删除,是因为表单的删除可能用户并没有点保存,点击关闭表单,数据还要保持存在)
				List<String> deleteAttachmentList = new ArrayList<>();
//				List<GovDocAttachment> readyDelete = govDocAttachmentDao.getAttachmentListByDocument(businessKey);
				List<GovDocAttachment> readyDelete =new ArrayList<>();

				//处理附件被删除问题 20250208 start
				if(initAList!=null && !initAList.isEmpty()) {
					readyDelete =govDocAttachmentDao.getAttachmentListByRealIds(initAList);
				}
				//处理附件被删除问题 20250208 end


				for(int j=0;j<readyDelete.size();j++) {
					GovDocAttachment readyOne = readyDelete.get(j);
					Boolean flag = false;
					for(int i=0;i<list.size();i++) {
						GovDocAttachment listOne = list.get(i);
						if(readyOne.getId().equals(listOne.getId())) {//老的数据有和新的附件有相同的  为非删除的数据
							flag = true;
							break;
						}
					}
					if(!flag) {//老数据没有和新附件数据匹配,为删除数据
						deleteAttachmentList.add(readyOne.getId());
						deleteupdateRecord.put(readyOne.getId(),new String[] {readyOne.getAttachmentName(),readyOne.getDocumentSource().toString(),readyOne.getDocumentId()});
					}
				}

				//对于每条附件进行绑定主表关联
				for(int j=0;j<list.size();j++) {
					GovDocAttachment attachment = list.get(j);
					//附件签批 暂时注释不需要提交的时候处理转版
					/*if("1".equals(enableHandSignature)){
						String displayName = attachment.getAttachmentName();
						displayName = displayName.substring(0, displayName.lastIndexOf("."));
						Map<String, Object> tarnsMap = this.transofdByFileId(attachment.getSysAttchmentId(),"","",displayName,".ofd");
						if(tarnsMap!=null&&tarnsMap.size()>0){
							//默认多文件
							String tarnsAttId = StringUtils.null2String(tarnsMap.get("id"));
							signApproveFileService.saveSignApproveAttTemp(businessKey,taskId,attachment.getSysAttchmentId(),tarnsAttId);
							attachment.setSignAttId(tarnsAttId);
						}
					}*/
					if(StringUtils.isEmpty(attachment.getDocumentId())) {//没有绑定主表id
						attachment.setDocumentId(businessKey);
						addupdateRecord.put(attachment.getId(),new String[] {attachment.getAttachmentName(),attachment.getDocumentSource().toString(),businessKey});

					}else {//已绑定主表id
						if(!attachment.getDocumentId().equals(businessKey)) {//过滤和主表无关的附件
							if (StringUtils.isNotEmpty(attachment.getSysAttchmentId())) {
								Map attaMap = copyFileUtils.copyFileByAttachId(attachment.getSysAttchmentId(), attachment.getAttachmentName());
								GovDocAttachment newGovDocAttachment = new GovDocAttachment();
								newGovDocAttachment.setAttachmentName(attachment.getAttachmentName());
								newGovDocAttachment.setAttachmentReal(attaMap.get("fileName").toString());
								newGovDocAttachment.setCorpId(attachment.getCorpId());
								newGovDocAttachment.setDocumentId(businessKey);
								newGovDocAttachment.setIsDelete(0);
								newGovDocAttachment.setDocumentSource(attachment.getDocumentSource());
								newGovDocAttachment.setFileSize(Long.valueOf(attaMap.get("fileSize").toString()));
								newGovDocAttachment.setFileSource(attachment.getFileSource());
								newGovDocAttachment.setSecurityClassificat(attachment.getSecurityClassificat());
								newGovDocAttachment.setSysAttchmentId(attaMap.get("id").toString());
								newGovDocAttachment.setVersion(attachment.getVersion());
								//newGovDocAttachment.setSortNo(Integer.valueOf(list.size()-j));
								newGovDocAttachment.setSortNo(Integer.valueOf(j+1));
								newList.add(newGovDocAttachment);
								//处理附件对应的签批件
								handleAttSign(businessKey,taskId,attachment.getDocumentId(),attachment.getSysAttchmentId(),attaMap.get("id").toString());
							}
							continue;
						}
					}
					//处理密级
					if(fileSecurityList!=null&&!"".equals(fileSecurityList)) {
						JSONObject fileSecurityJson = JSONObject.parseObject(fileSecurityList);
						try {
							if(fileSecurityJson.getString(attachment.getId())!=null) {
								if(StringUtils.isEmpty(attachment.getSecurityClassificat())) {
									String newSecurity = "";
									if(!fileSecurityJson.getString(attachment.getId()).equals("-1")) {
										newSecurity = StringUtils.null2String(securityMap.get(fileSecurityJson.getString(attachment.getId())));
									}
									if(StringUtils.isNotEmpty(newSecurity)) {
										updateupdateRecord.put(attachment.getId(),new String[]{"",newSecurity,attachment.getAttachmentName(),attachment.getDocumentSource().toString(),attachment.getDocumentId()});
									}
								}else {
									if(!attachment.getSecurityClassificat().equals(fileSecurityJson.getString(attachment.getId()))) {
										String oldSecurity = StringUtils.null2String(securityMap.get(attachment.getSecurityClassificat()));
										String newSecurity = "";
										if(!fileSecurityJson.getString(attachment.getId()).equals("-1")) {
											newSecurity = StringUtils.null2String(securityMap.get(fileSecurityJson.getString(attachment.getId())));
										}
										if(StringUtils.isNotEmpty(newSecurity)||StringUtils.isNotEmpty(oldSecurity)) {
											updateupdateRecord.put(attachment.getId(),new String[]{oldSecurity,newSecurity,attachment.getAttachmentName(),attachment.getDocumentSource().toString(),attachment.getDocumentId()});
										}
									}
								}
								if(!fileSecurityJson.getString(attachment.getId()).equals("-1")) {
									attachment.setSecurityClassificat(fileSecurityJson.getString(attachment.getId()));
									// 更新系统附件密级
									Map paramParams = new HashMap<>();
									paramParams.put("fid", attachment.getSysAttchmentId());
									paramParams.put("fileSecretLevel", attachment.getSecurityClassificat());
									attachmentUtilsService.updateAttachmentSecretLevel(paramParams,user.getJwtToken());
								}else {
									attachment.setSecurityClassificat(null);
								}
							}
						}catch(Exception e) {
							e.printStackTrace();
						}
					}
					if(StringUtils.isNotBlank(attachment.getParentDocumentId())&&StringUtils.isNotBlank(attachment.getParentSysAttchmentId())){
						//处理附件对应的签批件
						handleAttSign(businessKey,taskId,attachment.getParentDocumentId(),attachment.getParentSysAttchmentId(),attachment.getSysAttchmentId());
					}
					newList.add(attachment);
				}
				//批量新增数据
				this.govDocAttachmentService.save(newList);
				//删除数据
				if(deleteAttachmentList!=null && !deleteAttachmentList.isEmpty()) {
					this.govDocAttachmentService.deleteAttachByIds(deleteAttachmentList);
				}
				List<GovUpdateRecord> updateRecordList = new ArrayList<>();
				//处理修改记录
				Boolean typeFlag = true;
				if(StringUtils.isNotEmpty(type)&&("0".equals(type)||"1".equals(type))) {
					typeFlag = false;
				}
				if(StringUtils.isNotEmpty(permissionCode)&&("draft".equals(permissionCode)||"start".equals(permissionCode))){
					typeFlag = false;
				}
				if(typeFlag) {
					if(addupdateRecord!=null&&addupdateRecord.size()>0) {
						//如果有修改记录则已新增为主
						for(String addRecord:addupdateRecord.keySet()){
							String[] addRecordObject = (String[])addupdateRecord.get(addRecord);
							if(updateupdateRecord!=null&&updateupdateRecord.get(addRecord)!=null) {
								updateupdateRecord.remove(addRecord);
							}
							if(StringUtils.isNotEmpty(addRecordObject[2])) {
								GovUpdateRecord addOne = new GovUpdateRecord();
								addOne.setDocumentSource(Integer.parseInt(addRecordObject[1]));
								addOne.setFlowBusinesskey(addRecordObject[2]);
								String content = "上传附件:"+addRecordObject[0];
								addOne.setUpdateRecord(content);
								updateRecordList.add(addOne);
							}
						}

					}
					if(updateupdateRecord!=null&&updateupdateRecord.size()>0) {
						for(String updateRecord:updateupdateRecord.keySet()) {
							String[] updateRecordObject = (String[])updateupdateRecord.get(updateRecord);
							if(StringUtils.isNotEmpty(updateRecordObject[4])) {
								GovUpdateRecord updateOne = new GovUpdateRecord();
								updateOne.setDocumentSource(Integer.parseInt(updateRecordObject[3]));
								updateOne.setFlowBusinesskey(updateRecordObject[4]);
								String oldSec = updateRecordObject[0];
								if(StringUtils.isEmpty(updateRecordObject[0])) {
									oldSec = "空";
								}
								String newSec = updateRecordObject[1];
								if(StringUtils.isEmpty(updateRecordObject[1])) {
									newSec = "空";
								}
								String content = updateRecordObject[2]+"的【密级】由"+oldSec+"改为"+newSec;
								updateOne.setUpdateRecord(content);
								updateRecordList.add(updateOne);
							}
						}
					}
					if(deleteupdateRecord!=null&&deleteupdateRecord.size()>0) {
						for(String deleteRecord:deleteupdateRecord.keySet()){
							String[] deleteRecordObject = (String[])deleteupdateRecord.get(deleteRecord);
							if(StringUtils.isNotEmpty(deleteRecordObject[2])) {
								GovUpdateRecord deleteOne = new GovUpdateRecord();
								deleteOne.setDocumentSource(Integer.parseInt(deleteRecordObject[1]));
								deleteOne.setFlowBusinesskey(deleteRecordObject[2]);
								String content = "删除附件:"+deleteRecordObject[0];
								deleteOne.setUpdateRecord(content);
								updateRecordList.add(deleteOne);
							}
						}
					}
					if(CollectionUtils.isNotEmpty(updateRecordList)) {
						govRelRecordService.save(updateRecordList);
					}
				}

			}
		}else {//清空关联的附件
			//删除的记录 {id:[名字,来源,绑定的关联主表id]}
			if(!StringUtils.isEmpty(businessKey)) {
				//处理附件被删除问题 20250208 start
				List<String> initAList = new ArrayList<String>();
				if(initAttachmentList!=null&&!"".equals(initAttachmentList)) {
					String[] initAttachmentArr = initAttachmentList.split("\\|");
					for(int i=0;i<initAttachmentArr.length;i++) {
						initAList.add(initAttachmentArr[i]);
					}
				}
				//处理附件被删除问题 20250208 end
				List<GovDocAttachment> deleteList = new ArrayList<>();
				//处理附件被删除问题 20250208 start
				if(initAList!=null && !initAList.isEmpty()) {
					deleteList = this.govDocAttachmentDao.getAttachmentListByRealIds(initAList);
				}
				//List<GovDocAttachment> deleteList = this.govDocAttachmentDao.getAttachmentListByDocument(businessKey);
				if(CollectionUtils.isNotEmpty(deleteList)) {
					List<String> deleteAttachmentList = new ArrayList<>();
					List<GovUpdateRecord> updateRecordList = new ArrayList<>();
					for(int i=0;i<deleteList.size();i++) {
						GovDocAttachment readyOne = deleteList.get(i);
						GovUpdateRecord deleteOne = new GovUpdateRecord();
						deleteOne.setDocumentSource(Integer.parseInt(readyOne.getDocumentSource().toString()));
						deleteOne.setFlowBusinesskey(readyOne.getDocumentId());
						String content = "删除附件:"+readyOne.getAttachmentName();
						deleteOne.setUpdateRecord(content);
						updateRecordList.add(deleteOne);
						deleteAttachmentList.add(readyOne.getId());
					}
					if(CollectionUtils.isNotEmpty(updateRecordList)) {
						govRelRecordService.save(updateRecordList);
					}
					//删除数据
					if(CollectionUtils.isNotEmpty(deleteAttachmentList)) {
						this.govDocAttachmentService.deleteAttachByIds(deleteAttachmentList);
					}
				}
			}

		}
	}


	/**
	 * 处理附件对应的签批件
	 * @param dataId
	 * @param taskId
	 * @param parentDataId
	 * @param parentSysAttId
	 * @param sysAttId
	 */
	public void handleAttSign(String dataId,String taskId,String parentDataId,String parentSysAttId,String sysAttId){
		logger.info("=======handleAttSign=====start=======");
		//首先查询到签批模板表数据进行复制处理
		logger.info("=======handleAttSign=====parentDataId:{}====parentSysAttId:{}===",parentDataId,parentSysAttId);
		GoaDocSignApproveFile attSignFile = signApproveFileService.findApproveAttFileInfo(parentDataId,parentSysAttId);
		if(null==attSignFile){
			return;
		}
		String signFileId = attSignFile.getFileId();
		Map copyFileMap = copyFileUtils.copyFileByAttachId(signFileId, "");

		Map<String,String> signApproveFileMap = signApproveFileService.saveSignApproveAttTemp(dataId,taskId,sysAttId,signFileId);
		String signId = signApproveFileMap.get("signId");
		//根据之前模板签批信息：查找对应的签批表数据，进行复制处理
		List<GovDocFileEdition> attEditionList = signApproveFileService.getAttEditionList(attSignFile.getGoaId(),attSignFile.getId(),"5");
		List<GovDocFileEdition> saveEditionList = new ArrayList<>();
		for(GovDocFileEdition attEdition:attEditionList){
			Map copyAttEditionMap = copyFileUtils.copyFileByAttachId(attEdition.getFileId(), "");
			if (copyAttEditionMap != null && copyAttEditionMap.size() > 0) {
				String signTextApproveId = "";
				String signTextApproveFileExt = StringUtils.null2String(copyAttEditionMap.get("fileExt"));
				String fileName = StringUtils.null2String(copyAttEditionMap.get("fileName"));
				String fileId = StringUtils.null2String(copyAttEditionMap.get("id"));
				String checksum = StringUtils.null2String(copyAttEditionMap.get("checksum"));
				if (StringUtils.isNotBlank(fileName)) {
					signTextApproveId = fileName.substring(0, fileName.lastIndexOf("."));
				}
				if (StringUtils.isNotBlank(signTextApproveFileExt)) {
					signTextApproveFileExt = signTextApproveFileExt.replace(".", "");
				}
				if (StringUtils.isNotBlank(signTextApproveId) && StringUtils.isNotBlank(signTextApproveFileExt)) {
					//保存一份不显示的正文签批记录,防止每次打开都复制生成
					GovDocFileEdition newFileEdition = new 	GovDocFileEdition();
					String attEditionStr = JSONObject.toJSONString(attEdition);
					newFileEdition = JSONObject.parseObject(attEditionStr, GovDocFileEdition.class);
					newFileEdition.setId(UuidUtils.UUID());
					newFileEdition.setFileId(fileId);
					newFileEdition.setRecordId(signTextApproveId);
					newFileEdition.setChecksum(checksum);
					newFileEdition.setSignId(signId);
					newFileEdition.setGoaId(dataId);
					saveEditionList.add(newFileEdition);
				}
			}
		}
		fileEditionService.save(saveEditionList);
	}

	/**
	 * @name: saveDocHandling
	 * @description: 转文记录相关公文
	 * @param user
	 * @param type
	 * @param businessKey
	 * @param flag
	 * @param oldInstanceid
	 * @param newInstanceid
	 * @param title
	 * @param distributeType
	 * @param distributeUserId
	 * @param disRecordId
	 * @param menuType
	 * @return: java.lang.Object
	 * @date: 2021/5/26 9:13
	 * @auther: fsx
	 *
	 */
	public Object saveDocHandling(WebUser user, String type, String businessKey, String flag, String oldInstanceid, String newInstanceid, String title, String distributeType, String distributeUserId, String disRecordId,String menuType) {
		//不知道上面谁获取的disRecordId值与distributeUserId一样，感觉不对，所以下面重新赋值 by wandz 20210318
		if(StringUtils.isNotEmpty(distributeUserId)) {
			GovDistributeUser dEntity = disUserService.findOne(distributeUserId,true);
			disRecordId = dEntity.getDisRecordId();
		}
		if("draft".equals(menuType)) {
			// 草稿箱保存,判断是否已有记录,若有则更新,若没有,什么都不做
			GovDocHandling docHandling = govDocHandlingService.getHandlingByGoaId(businessKey);
			if(docHandling == null) {
				return  null;
			}
		}
		//获取分发的表id串
		String disRecordIdstr = govDocHandlingService.getHandlingInfo(oldInstanceid,disRecordId);
		// 保存草稿
		if("0".equals(flag)) {
			GovDocHandling docHandling = new GovDocHandling();
			docHandling.setGoaId(businessKey);
			docHandling.setTitle(title);
			docHandling.setInitiationTime(new Date());
			//String  currentOrgId = govLayoutFileDao.getCurrentOrgIdbyUserId(user.getUserId());
			//使用缓存中的数据
			docHandling.setInitiationUnit(user.getInstitutionId());
			docHandling.setInitiationUnitName(user.getInstitutionName());
			docHandling.setPromoter(user.getUserId());
			docHandling.setPromoterName(user.getCnName());
			docHandling.setType(type);
			docHandling.setProcessInstanceId(oldInstanceid);
			docHandling.setRelationId(newInstanceid);
			docHandling.setDistributeType(distributeType);
			docHandling.setDistributeUserId(distributeUserId);
			docHandling.setIsDraft(flag);
			docHandling.setDisRecordId(disRecordId);
			docHandling.setDisRecordIdstr(disRecordIdstr);
			govDocHandlingService.save(docHandling);
		}else {
			// 新建,判断该条记录是否已保存,若是,则更新isDraft状态
			GovDocHandling docHandling = govDocHandlingService.getHandlingByGoaId(businessKey);
			if(docHandling == null) {
				docHandling = new GovDocHandling();
				docHandling.setGoaId(businessKey);
				docHandling.setTitle(title);
				docHandling.setInitiationTime(new Date());
				/*String  currentOrgId = govLayoutFileDao.getCurrentOrgIdbyUserId(user.getUserId());
				String currentOrgName = govLayoutFileDao.getOrgNameByid(currentOrgId);
				String orgName = currentOrgName;*/
				docHandling.setInitiationUnit(user.getInstitutionId());
				docHandling.setPromoter(user.getUserId());
				docHandling.setInitiationUnitName(user.getInstitutionName());
				docHandling.setPromoterName(user.getCnName());
				docHandling.setType(type);
				docHandling.setProcessInstanceId(oldInstanceid);
				docHandling.setRelationId(newInstanceid);
				docHandling.setDistributeType(distributeType);
				docHandling.setDistributeUserId(distributeUserId);
				docHandling.setIsDraft(flag);
				docHandling.setDisRecordId(disRecordId);
				docHandling.setDisRecordIdstr(disRecordIdstr);
			}else {
				docHandling.setIsDraft("1");
			}
			govDocHandlingService.save(docHandling);
			// 添加日志
			String logTitle =docHandling.getTitle();
			if (StringUtils.isBlank(logTitle) && StringUtils.isNotBlank(docHandling.getProcessInstanceId())) {
				List<Map> sendFileInfoByProcId = govDocHandlingService.getTitleByProcId(docHandling.getProcessInstanceId());
				if (sendFileInfoByProcId != null && !sendFileInfoByProcId.isEmpty()) {
					logTitle = sendFileInfoByProcId.get(0).get("text_").toString();
				}
			}
			// 添加日志
			String logTitleRead =docHandling.getTitle();
			if (StringUtils.isBlank(logTitleRead) &&  StringUtils.isNotBlank(docHandling.getDisRecordId())) {
				GovDistributeUser distributeUser = disUserService.findOne(docHandling.getDisRecordId());
				if (distributeUser != null ) {
					logTitleRead = distributeUser.getDisTitle();
				}
			}
			switch (docHandling.getDistributeType()) {
				case "1": //待办
					if("1".equals(docHandling.getType())&&logService.checkOptLog("0", LogConstant.GOA_DOCUMENT_PENDING_ZFW, user.getJwtToken())) {
						logService.saveModuleLog(LogConstant.GOA_DOCUMENT_PENDING_ZFW, logTitle, "");
					}else if("2".equals(docHandling.getType())&&logService.checkOptLog("0", LogConstant.GOA_DOCUMENT_PENDING_ZSW, user.getJwtToken())) {
						logService.saveModuleLog(LogConstant.GOA_DOCUMENT_PENDING_ZSW, logTitle, "");
					}else if("3".equals(docHandling.getType())&&logService.checkOptLog("0", LogConstant.GOA_DOCUMENT_PENDING_ZQB, user.getJwtToken())) {
						logService.saveModuleLog(LogConstant.GOA_DOCUMENT_PENDING_ZQB, logTitle, "");
					}
					break;
				case "2": //已办
					if("1".equals(docHandling.getType())&&logService.checkOptLog("0", LogConstant.GOA_DOCUMENT_DONE_ZFW, user.getJwtToken())) {
						logService.saveModuleLog(LogConstant.GOA_DOCUMENT_DONE_ZFW, logTitle, "");
					}else if("2".equals(docHandling.getType())&&logService.checkOptLog("0", LogConstant.GOA_DOCUMENT_DONE_ZSW, user.getJwtToken())) {
						logService.saveModuleLog(LogConstant.GOA_DOCUMENT_DONE_ZSW, logTitle, "");
					}else if("3".equals(docHandling.getType())&&logService.checkOptLog("0", LogConstant.GOA_DOCUMENT_DONE_ZQB, user.getJwtToken())) {
						logService.saveModuleLog(LogConstant.GOA_DOCUMENT_DONE_ZQB, logTitle, "");
					}
					break;
				case "3": //待阅
					if("1".equals(docHandling.getType())&&logService.checkOptLog("0", LogConstant.GOA_DOCUMENT_UNREAD_ZFW, user.getJwtToken())) {
						logService.saveModuleLog(LogConstant.GOA_DOCUMENT_UNREAD_ZFW, logTitleRead, "");
					}else if("2".equals(docHandling.getType())&&logService.checkOptLog("0", LogConstant.GOA_DOCUMENT_UNREAD_ZSW, user.getJwtToken())) {
						logService.saveModuleLog(LogConstant.GOA_DOCUMENT_UNREAD_ZSW, logTitleRead, "");
					}else if("3".equals(docHandling.getType())&&logService.checkOptLog("0", LogConstant.GOA_DOCUMENT_UNREAD_ZQB, user.getJwtToken())) {
						logService.saveModuleLog(LogConstant.GOA_DOCUMENT_UNREAD_ZQB, logTitleRead, "");
					}else if("4".equals(docHandling.getType())&&logService.checkOptLog("0", LogConstant.GOA_DOCUMENT_UNREAD_ZSWDJ, user.getJwtToken())) {
						logService.saveModuleLog(LogConstant.GOA_DOCUMENT_UNREAD_ZSWDJ, logTitleRead, "");
					}
					break;
				case "4": //已阅
					if("1".equals(docHandling.getType())&&logService.checkOptLog("0", LogConstant.GOA_DOCUMENT_READ_ZFW, user.getJwtToken())) {
						logService.saveModuleLog(LogConstant.GOA_DOCUMENT_READ_ZFW, logTitleRead, "");
					}else if("2".equals(docHandling.getType())&&logService.checkOptLog("0", LogConstant.GOA_DOCUMENT_READ_ZSW, user.getJwtToken())) {
						logService.saveModuleLog(LogConstant.GOA_DOCUMENT_READ_ZSW, logTitleRead, "");
					}else if("3".equals(docHandling.getType())&&logService.checkOptLog("0", LogConstant.GOA_DOCUMENT_READ_ZQB, user.getJwtToken())) {
						logService.saveModuleLog(LogConstant.GOA_DOCUMENT_READ_ZQB, logTitleRead, "");
					}else if("4".equals(docHandling.getType())&&logService.checkOptLog("0", LogConstant.GOA_DOCUMENT_READ_ZSWDJ, user.getJwtToken())) {
						logService.saveModuleLog(LogConstant.GOA_DOCUMENT_READ_ZSWDJ, logTitleRead, "");
					}
					break;
				case "5": //我的发起
					if("1".equals(docHandling.getType())&&logService.checkOptLog("0", LogConstant.GOA_DOCUMENT_MY_ZFW, user.getJwtToken())) {
						logService.saveModuleLog(LogConstant.GOA_DOCUMENT_MY_ZFW, logTitle, "");
					}else if("2".equals(docHandling.getType())&&logService.checkOptLog("0", LogConstant.GOA_DOCUMENT_MY_ZSW, user.getJwtToken())) {
						logService.saveModuleLog(LogConstant.GOA_DOCUMENT_MY_ZSW, logTitle, "");
					}else if("3".equals(docHandling.getType())&&logService.checkOptLog("0", LogConstant.GOA_DOCUMENT_MY_ZQB, user.getJwtToken())) {
						logService.saveModuleLog(LogConstant.GOA_DOCUMENT_MY_ZQB, logTitle, "");
					}
					break;
				case "6": // 收文登记
					//办理记录表处理
					String handName = "";
					if("1".equals(docHandling.getType())) {
						handName = "转发文";
					}else if("2".equals(docHandling.getType())) {
						handName = "转收文";
					}else if("3".equals(docHandling.getType())) {
						handName = "转签报";
					}
					GoaDocRegisterRecord goaDocRegisterRecord = new GoaDocRegisterRecord();
					goaDocRegisterRecord.setHandName(handName);
					goaDocRegisterRecord.setHandStatus(docHandling.getType());
					goaDocRegisterRecord.setRegisterId(docHandling.getProcessInstanceId());
					goaDocRegisterRecord.setIsDelete(0);
					goaDocRegisterRecord.setCreatedUserName(user.getUserName());
					goaDocRegisterRecordService.save(goaDocRegisterRecord);
					// 更新主表状态
					GoaDocRegister goaDocRegister = govRegisterService.findOne(docHandling.getProcessInstanceId());
					if(goaDocRegister != null) {
						if(StringUtils.isNotEmpty(goaDocRegister.getHandingStatus())) {
							if(!goaDocRegister.getHandingStatus().contains(docHandling.getType())) {
								goaDocRegister.setHandingStatus(goaDocRegister.getHandingStatus()+","+docHandling.getType());
							}
						}else {
							goaDocRegister.setHandingStatus(docHandling.getType());
						}
						govRegisterService.save(goaDocRegister);
					}
					if("1".equals(docHandling.getType())&&logService.checkOptLog("0", LogConstant.RECEIVEREGISTER_LOG_07, user.getJwtToken())) {
						logService.saveModuleLog(LogConstant.RECEIVEREGISTER_LOG_07, docHandling.getTitle(), "");
					}else if("2".equals(docHandling.getType())&&logService.checkOptLog("0", LogConstant.RECEIVEREGISTER_LOG_08, user.getJwtToken())) {
						logService.saveModuleLog(LogConstant.RECEIVEREGISTER_LOG_08, docHandling.getTitle(), "");
					}else if("3".equals(docHandling.getType())&&logService.checkOptLog("0", LogConstant.RECEIVEREGISTER_LOG_09, user.getJwtToken())) {
						logService.saveModuleLog(LogConstant.RECEIVEREGISTER_LOG_09, docHandling.getTitle(), "");
					}
					break;
			}
		}
		return  null;
	}

	/**
	 * 还原
	 * @param ids
	 * @return
	 */
	public OperationResult restore(HttpServletRequest request,String ids, String processInstanceId, WebUser user, String corpId, String token) {
		try {
			if(StringUtils.isNotEmpty(ids)) {
				List<String> list = new ArrayList<String>();
				String[] split = ids.split(",");
				for (int i = 0; i < split.length; i++) {
					String fileId = "";
					String serialNumber = "";
					GovDocdelrecord govDocdelrecord = govScrapBoxService.findOne(split[i]);
					String businesstable = govDocdelrecord.getBusinesstable();
					String businesskey = govDocdelrecord.getBusinesskey();
					String flowStatus = govDocdelrecord.getFlowStatus();
					if (StringUtils.isNotEmpty(businesstable) && StringUtils.isNotEmpty(businesskey)) {
						if ("goa_doc_sendfile".equals(businesstable)) {
							GovSendFile sendFile = this.findOne(businesskey);
							fileId = sendFile.getId();
							serialNumber = sendFile.getSerialNumber();
							sendFile.setBlnDelete("0");
							govSendFileDao.restoreByIds(fileId,flowStatus);
							//govSendFileDao.updateSaveFileNoStatus(findOne.getIssuedNumber());
							if (StringUtils.isNotBlank(sendFile.getFileNoSee())) {
								Map<String, Object> judgeIsUsed = govSendFileDao.judgeIsUsed(sendFile.getFileNoSee());
								if (judgeIsUsed.size()>0) {
									String fileNoId = (String) judgeIsUsed.get("fileNoId");
									String str = sendFile.getIssuedNumber();
									String newwh = "";
									String newStr = "";
									String jgdz = "";
									String nf  = "";
								    String hm = "";
								    String wh = sendFile.getFileNoSee();
									//机关带子，年份，号码
								    if (null!=str) {
								    	if(str.indexOf("]")>-1){//不显示文号名
											newStr = str.split("]")[1];
											jgdz = str.split("]")[0].replace("[","");
											if(newStr.indexOf('-')>-1){//不显示年份
												nf = newStr.split("-")[1];
												hm=	newStr.split("-")[2];
												if (hm.indexOf("|") > -1) {
								    				hm=	hm.split("\\|")[1];
												}
											}else {
												hm = newStr.split("〕")[1];
												if (hm.indexOf("|") > -1) {
								    				hm=	hm.split("\\|")[1];
												}
												nf=	newStr.split("〕")[0].split("〔")[1];
											}
										}else if(str.indexOf(')')>-1){//显示文号名
											jgdz = str.split("\\)")[0].replace("(","");
											newStr = str.split("\\)")[1];
											if(newStr.indexOf('-')>-1){//不显示年份
												nf = newStr.split("-")[1];
												hm=	newStr.split("-")[2];
												if (hm.indexOf("|") > -1) {
								    				hm=	hm.split("\\|")[1];
												}
											}else {
												hm = newStr.split("〕")[1];
												if (hm.indexOf("|") > -1) {
								    				hm=	hm.split("\\|")[1];
												}
								    			nf=	newStr.split("〕")[0].split("〔")[1];
											}
										}else{
											newStr = str;
										}
									}
									  //删除旧的，插入一个新的值。
								    String createdBy = sendFile.getCreatedBy();
								    String useName = "";
								    if (StringUtils.isNotEmpty(createdBy)) {
								    	Map<String, Object> user2 = userApiService.getUser(createdBy, user.getCorpId(), null, user.getJwtToken());
								    	useName = (String) user2.get("userName");
									}
									DocSendSavefileno saveSendFileNo = govSendSaveFileNoService.addSendFileNo(wh,nf,hm,useName,fileNoId);
									sendFile.setSavefilenoId(saveSendFileNo.getId());
								}
							}
							this.save(sendFile);

						}else if ("goa_doc_receivefile".equals(businesstable)) {
							GovDocReceiveFile receiveFile = govDocReceiveFileService.findOne(businesskey);
							fileId = receiveFile.getId();
							serialNumber = receiveFile.getSerialNumber();
							receiveFile.setBlnDelete("0");
							govDocReceiveFileService.save(receiveFile);
						}else if ("goa_doc_signreport".equals(businesstable)) {
							DocSignreport signreport = docSignreportService.findOne(businesskey);
							fileId = signreport.getId();
							serialNumber = signreport.getSerialNumber();
							//恢复数据
							signQuery.reductionByIds(fileId);
						}else if ("goa_register".equals(businesstable)) {
							GoaDocRegister docRegister = govRegisterService.findOne(businesskey);
							docRegister.setIsDelete(0);
							govRegisterService.save(docRegister);
							return OperationResult.buildSuccessResult("还原成功");
						}
					}
					list.add(fileId);
					// 判断这条数据是分发、转发、转阅、还是传阅
					List<Map<String, String>> queryMaps = govDistributeRecordDao.queryDistributeUserAndRecord(fileId);
					if (queryMaps != null && queryMaps.size() > 0) {
						for (Map<String, String> itemMap : queryMaps) {
							String source = itemMap.get("source");
							String receive_user_idstr = itemMap.get("receive_user_idstr");
							String task_id = itemMap.get("task_id");
							String title = itemMap.get("title");
							String remindContent = itemMap.get("remindContent");
							String receiverType = itemMap.get("receiverType");
							String dataId = task_id+source;
							if ("3".equals(source) || "4".equals(source)) {
								// 删除统一消息来自转阅、传阅的待阅列表数据
								String[] recArr = receive_user_idstr.split(",");
								String msgReceiverStr = "";
								for (String rec : recArr) {
									msgReceiverStr += "{\"10\":\"" + rec + "\"},";
								}
								if (StringUtils.isNotEmpty(msgReceiverStr)) {
									msgReceiverStr = msgReceiverStr.substring(0, msgReceiverStr.length() - 1);
								}
								  //推送信息
				    			Map<String, String> para = new HashMap<String, String>();
				    	        para.put("userId", user.getUserId());
				    	        para.put("corpId", user.getCorpId());
				    	        para.put("token", user.getJwtToken());
				    	        para.put("dataId", fileId);
				    	        para.put("type", "modal");
				    	        para.put("title", title);
				    	        para.put("msgType", "1");
				    	        //发送人
				    	        para.put("sendUserName", user.getCnName());
				    	        //发送时间
				    	        para.put("sendTime", sdf.format(new Date()));
				    	        //消息标题
				    	        para.put("reminderContent", remindContent);
				    	        //消息内容
				    	        para.put("messageContent", remindContent);
				    	        para.put("msgTitle", title);
				    	        para.put("msgContent", remindContent);
				                para.put("openMode", "1");
				    	        para.put("url", "goa/document/readpassage/readpassage_detail.html");
				    	        para.put("infoFlag", "recommend");
				    	        para.put("msgReceiver", msgReceiverStr);
				    	        para.put("id", fileId);

				    	        para.put("receiveUserIds", msgReceiverStr);
				    	        para.put("senderUserIds", user.getUserId());
				    	        para.put("sendType", receiverType);
				    	        para.put("msgLink", "goa/document/readpassage/readpassage_detail.html");
				    	        goaCommonUtils.pushMessage(para,request);
							}
						}
					}
					//判断这条收藏数据是分发、转发、转阅、还是传阅
					List<Map<String,String>> queryMap = govCollectionDao.queryCollectionDataFromWhere(corpId, fileId);
					if(queryMap!=null && queryMap.size()>0) {
						for (Map<String, String> itemMap : queryMap) {
							String source = itemMap.get("source");
							String id = itemMap.get("id");
							if("3".equals(source) || "4".equals(source)) {
								//恢复收藏夹数据
								govCollectionDao.reductionAllCollectionInfo(id);
							}
						}
					}
					//恢复流水号
					restoreBizCode(user,fileId,serialNumber);
					//删还原，待阅，已阅文件
					govDistributeRecordService.reductionDistributeRecord("1", fileId);
					//还原退回列表数据
					govFlowBackDao.reductionBackDataStatus(fileId);
				}
				//还原待办，我的发起收藏夹数据
				logger.info("删除收藏夹数据："+ids);
				govCollectionDao.restoreCollectionInfo(corpId, list);
				//还原关注列表数据
				logger.info("删除关注数据：processInstanceId"+processInstanceId);
				govMyAttentionDao.reductionAttention(processInstanceId);
				// 删除流程实例
				Map<String, String> params = new HashMap<String, String>();
	            params.put("userId", user.getUserId());
	            params.put("corpId", corpId);
	            params.put("processInstanceId", processInstanceId);
	            //流程的还原还没有做。所以此处删除流程实例
	    	    bpmApiService.deleteProcessInstance(params,user.getJwtToken());
			}
			return OperationResult.buildSuccessResult("还原成功");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("还原失败"+e);
			return OperationResult.buildFailureResult("还原失败");
		}
	}

	/**
	 * @name: releaseBizCode
	 * @description: 恢复流水号
	 * @param user
	 * @param dataId
	 * @param serialNumber
	 * @return: void
	 * @date: 2021/4/20 16:17
	 * @auther: fsx
	 *
	 */
	public void restoreBizCode(WebUser user,String dataId, String serialNumber) {
		if (StringUtils.isNotEmpty(serialNumber)){
			Map<String, String> paramMap = new HashMap<String, String>();
			List<Map> list = goaDocBizcodeProcessService.getRuleIdByDataId(dataId);
            for (Map map : list) {
            	String ruleId = map.get("ruleId")==null?"":map.get("ruleId")+"";
            	if (StringUtils.isNotEmpty(ruleId)) {
            		paramMap.put("bizCodeValue",ruleId);
        			paramMap.put("bizCode",serialNumber);
        			paramMap.put("dataId",dataId);
        			org.ezplatform.util.RestClient restClient = new org.ezplatform.util.RestClient(true);
        			bizcodeApiService.updateBizCode(paramMap,user.getJwtToken());
				}
			}
		}
	}

	public Map<String,Object> getVersion(String id){
		return govSendFileDao.getVersion(id);
	}

	public List<Map> getAllSendFileInfo(String page,String pageSize) {
		Map<String, Object> paramMap = new HashMap<>();
		StringBuffer sql = new StringBuffer();
		sql.append(" select DISTINCT t.title title,t.id id,ahp.PROC_INST_ID_ processInstanceId,t.createdBy createdBy,t.createdDate createdDate from ");
		sql.append(" goa_doc_sendfile t inner join ACT_HI_PROCINST ahp on t.id = ahp.BUSINESS_KEY_  and ahp.EXT_CATEGORY = 'goa_doc_sendfile' ");
		sql.append(" INNER JOIN act_hi_taskinst aht on aht.PROC_INST_ID_= ahp.ID_ ");
		sql.append(" where (t.bln_delete='0' or  t.bln_delete is null) and (aht.ext_bussinesskey is not null and aht.ext_bussinesskey != '') ");
		int size = 0;
		int no = 0;
		if (StringUtils.isNotEmpty(pageSize)) {
			size = Integer.valueOf(pageSize);
		}
		if (StringUtils.isNotEmpty(page)) {
		    no = Integer.valueOf(page);
		}
		int start = (no - 1) * size;
		return super.findByListNativeQuery(sql.toString(),"", paramMap,start,size);
	}


	public List<Map> getTaskIdByProcId(String processInstanceId) {
		Map<String, Object> paramMap = new HashMap<>();
		StringBuffer sql = new StringBuffer();
		sql.append(" select RES.id_  as taskId,I.user_id_ as userId from act_ru_task  RES LEFT JOIN ACT_RU_IDENTITYLINK I ON I.TASK_ID_ = RES.ID_  where RES.PROC_INST_ID_ = :processInstanceId");
		paramMap.put("processInstanceId",processInstanceId);
		return this.findByListNativeQuery(sql.toString(),"",paramMap);
	}

	/**
	 * 判断用户是否在范围内
	 */
	public boolean isInScopeWithUserId(String userId,String scopeTable, String fieldDataTable, String fieldData, String fieldDataValue){
		boolean isInScope = false;
		try {
			if(StringUtils.isNotBlank(userId) && StringUtils.isNotBlank(scopeTable) && StringUtils.isNotBlank(fieldDataTable)
					&& StringUtils.isNotBlank(fieldData) && StringUtils.isNotBlank(fieldDataValue)){
				isInScope = cmpApplyScopeService.isInScope(userId,scopeTable,fieldDataTable,fieldData,fieldDataValue);
			}
		}catch (Exception e){
			logger.error("isInScopeWithUserId 判断用户是否在范围内 出错：", e);
		}
		return isInScope;
	}

	public OperationResult deleteFileNo(String ids) {
		try{
			if (StringUtils.isNotEmpty(ids)) {
				String[] split = ids.split(",");
				for (int i = 0; i < split.length; i++) {
					GovSendFile findOne = this.findOne(split[i]);
                    if (findOne != null) {
                        String fileNoSee = findOne.getFileNoSee();
                        //获取删除共同字号信息
                        List<String> nameList = getFileNoGroupName(findOne.getSavefilenoId(), fileNoSee);
                        if (CollectionUtils.isNotEmpty(nameList)) {
                            Integer a = govSendFileDao.deleteSaveFileNoList(nameList);
							//String sql = "delete from goa_doc_send_savefileno where file_no_name in (?1)";
							//Query query = this.getEntityManager().createNativeQuery(sql).setParameter(1,nameList);
							//int result = query.executeUpdate();
                        }
                    }
				}
				return OperationResult.buildSuccessResult("删除成功");
			}
		}catch (Exception e){
			logger.error("deleteBids222222222  文号释放失败：", e);
		}
		return OperationResult.buildFailureResult("删除失败");
	}

    /**
     * 获取删除共用字号名称
     * @param savefilenoId
     * @param fileNoSee
     * @return
     */
    public List<String> getFileNoGroupName(String savefilenoId, String fileNoSee) {
        List<String> nameList = new ArrayList<>();
        if (StringUtils.isNotBlank(savefilenoId) && StringUtils.isNotBlank(fileNoSee)) {
            DocSendSavefileno savefileno = govSendSaveFileNoService.findOne(savefilenoId);
            if (savefileno != null && savefileno.getFileNoId() != null) {
                String delFileNoId = savefileno.getFileNoId();
                List<String> fileNoIdList = new ArrayList<>();
                GovSendFileNum sendFileNum = govSendFileNumService.findOne(delFileNoId);
                String name = "";
                if (sendFileNum != null) {
                    String filenoGroupId = sendFileNum.getFilenoGroupId();
                    name = sendFileNum.getName();
                    if (StringUtils.isNotEmpty(filenoGroupId)) {
                        DocSendFilegroup sendFilegroup = govSendGroupFileService.findOne(filenoGroupId);
                        String filenoGroupAllid = sendFilegroup.getFilenoGroupAllid();
                        if (StringUtils.isNotEmpty(filenoGroupAllid)) {
                            String[] fileids = filenoGroupAllid.split(",");
                            fileNoIdList = Arrays.asList(fileids);
                        }
                    }
                }
                if (CollectionUtils.isNotEmpty(fileNoIdList) && StringUtils.isNotBlank(name)) {
                    for (String fileNoId : fileNoIdList) {
                        if (!delFileNoId.equals(fileNoId)) {
                            GovSendFileNum fileNum = govSendFileNumService.findOne(fileNoId);
                            if (fileNum != null) {
                                String replaceName = fileNoSee.replace(name, fileNum.getName());
                                nameList.add(replaceName);
                            }
                        }
                    }
                }
            }
        }
        nameList.add(fileNoSee);
        return nameList;
    }

    /**
     * 根据ID获取共用字号的信息
     * @param id
     * @return
     */
	public List<Map> getGroupInfoById(String id) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		String sql = " select usename, year,use_file_no,is_group from goa_doc_send_savefileno where id = :idStr ";
		paramMap.put("idStr", id);
		List<Map> list = super.findByListNativeQuery(sql, "", paramMap);
		return list;

	}

    /**
     * 根据共用字号的信息的信息获取其对应的共用字号ids
     * @param usename
     * @param year
     * @param useFileNo
     * @return
     */
	public List<String>  getGroupIdByInfo(String usename,String year, String useFileNo) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		StringBuffer sql = new StringBuffer();
		sql.append(" select ID from goa_doc_send_savefileno where usename = :usename and year = :year and use_file_no = :useFileNo and is_group = '1' ");
		paramMap.put("usename", usename);
		paramMap.put("year", year);
		paramMap.put("useFileNo", useFileNo);
		List<String> result =  new ArrayList<>();
		List<Map> mainlist = super.findByListNativeQuery(sql.toString(), "", paramMap);
		if(mainlist!=null&&mainlist.size()>0) {
			for(Map map:mainlist) {
				result.add(map.get("ID")+"");
			}
		}

		return result;

	}


	public Map<String, Object> transofdByFileId(String fileId, String fileName, String moduleCode, String displayName, String fileExt) {
		Map<String, Object> dataMap = new HashMap<>();
		if (StringUtils.isNotBlank(fileId)) {
			WebUser user = WebUtils.getCurrentUser();
			String token = user.getJwtToken();
			moduleCode = StringUtils.isBlank(moduleCode)?"goa_document":moduleCode;
			//转换成版式文件
			Map<String, String> paramMap = new HashMap<>();
			paramMap.put("fileId", fileId);
			paramMap.put("fileName", fileName);
			paramMap.put("moduleCode", moduleCode);
			paramMap.put("fileSuffix", fileExt.replace(".",""));
			paramMap.put("ofdFileDisplayName", displayName);
			paramMap.put("fileExt", fileExt);
			String result = filetransformApiSevice.transformofd(paramMap, token);
			if (StringUtils.isNotBlank(result)) {
				Map<String, Object> resultMap = JsonUtils.readValue(result);
				if (resultMap != null && resultMap.size() > 0) {
					String type = StringUtils.null2String(resultMap.get("type"));
					if ("success".equals(type)) {
						dataMap = (Map<String, Object>) resultMap.get("data");
					}
				}
			}
		}
		return dataMap;
	}


	/**
	 * 重新转版保存版本的方法
	 * @param userId
	 * @param orgId
	 * @param corpId
	 * @param businessKey
	 * @param taskId
	 * @param recordId
	 * @param multipleSignApprove
	 * @param flag
	 * @param displayName
	 * @param fileType
	 * @param parentProcessInstanceId
	 * @param newInstanceid
	 * @param processName
	 * @param stampedTransferSeal
	 */
	public void saveTextApproveHistory(String userId,String orgId,String corpId, String businessKey, String taskId, String recordId, String multipleSignApprove, String flag, String displayName,
									   String fileType, String parentProcessInstanceId, String newInstanceid, String processName,String stampedTransferSeal) {
		if (StringUtils.isNotEmpty(recordId) && StringUtils.isNotEmpty(businessKey)) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("recordId", recordId);
			map.put("corpId", corpId);
			Map<String, Object> attachment = govDocAttachmentService.getFormatFileInfo(recordId);
			String rootProcessInstanceId = "";
			if (StringUtils.isEmpty(parentProcessInstanceId)){
				Map<String,String> parentMap = getParentProcessId(newInstanceid);
				if (parentMap != null && !parentMap.isEmpty()){
					parentProcessInstanceId = parentMap.get("parentProcessInstanceId");
					rootProcessInstanceId = parentMap.get("rootProcessInstanceId");
				}
			}
			logger.info("saveTextApproveHistory  attachment-------------------->"+attachment.toString());
			if (attachment != null) {
				String isHidden = "0";
				logger.info("saveTextApproveHistory  multipleSignApprove-------------------->"+multipleSignApprove);
				logger.info("saveTextApproveHistory  flag-------------------->"+flag);
				if("1".equals(multipleSignApprove) && (StringUtils.isBlank(flag) || "3".equals(flag) || "4".equals(flag))){
					//多文件签批时,保存不显示签批文件记录,提交后才显示
					isHidden = "1";
				}
				if (attachment.get("id") !=null && attachment.get("checksum") !=null) {
					Map<String,Object> saveHistoryFile = attachment;
					logger.info("saveTextApproveHistory  saveHistoryFile-------------------->"+saveHistoryFile.toString());

					if(!"1".equals(multipleSignApprove)){
						//同文件签批生成记录,复制一份版式文件
						String fileId = StringUtils.null2String(attachment.get("id"));
						String checksum = StringUtils.null2String(attachment.get("checksum"));
						String fileExt = StringUtils.null2String(attachment.get("file_ext"));
						saveHistoryFile = copyFileUtils.saveHistoryFile(fileId, checksum, "goa_doc_history",fileExt, displayName);
						logger.info("saveTextApproveHistory  saveHistoryFile-------------------->"+saveHistoryFile.toString());

					}
					List<GovDocFileEdition> listByTask = fileEditionService.getListByTask(businessKey, taskId,fileType,userId);
					logger.info("saveTextApproveHistory  listByTask-------------------->"+listByTask.toString());

					if (null == listByTask || listByTask.isEmpty()) {
						saveFileEdition(recordId, businessKey, taskId, userId,orgId, saveHistoryFile,fileType,isHidden,
								"0",parentProcessInstanceId,newInstanceid,processName,rootProcessInstanceId,stampedTransferSeal);
					}else {
						//当前环节保存过
						List<GovDocFileEdition> listByDoc = fileEditionService.getListByDoc(businessKey,fileType);
						GovDocFileEdition govDocFileEdition = listByDoc.get(0);
						logger.info("saveTextApproveHistory  govDocFileEdition-------------------->"+govDocFileEdition.toString());

						if (govDocFileEdition != null) {
							if (govDocFileEdition.getVersionName().equals(userId) ) {
								if(!"1".equals(multipleSignApprove)){
									//同文件签批删除复制的文件
									String token = JwtUtils.createJwtToken(GlobalConstant.X_APP_AUTH);
									attachmentUtilsService.delete(govDocFileEdition.getFileId(), govDocFileEdition.getChecksum(), token);
								}
								govDocFileEdition.setFileId(saveHistoryFile.get("id").toString());
								govDocFileEdition.setVersionTime(new Date());
								govDocFileEdition.setChecksum(saveHistoryFile.get("checksum").toString());
								govDocFileEdition.setIsHidden(isHidden);
								govDocFileEdition.setIsReview("0");
								govDocFileEdition.setIsSeal(stampedTransferSeal);//加盖分转章 1是 0否
								govDocFileEdition.setProcessName(processName);
								govDocFileEdition.setProcessId(newInstanceid);
								if (StringUtils.isNotEmpty(parentProcessInstanceId)){
									govDocFileEdition.setRootProcessId(rootProcessInstanceId);
									govDocFileEdition.setParentProcessId(parentProcessInstanceId);
								}else {
									govDocFileEdition.setRootProcessId(newInstanceid);
									govDocFileEdition.setParentProcessId(newInstanceid);
								}
								fileEditionService.save(govDocFileEdition);
							}else {
								logger.info("saveTextApproveHistory  fileType-------------------->"+fileType);
								saveFileEdition(recordId, businessKey, taskId, userId,orgId, saveHistoryFile,fileType,isHidden,
										"0", parentProcessInstanceId, newInstanceid, processName, rootProcessInstanceId,stampedTransferSeal);
							}

						}
					}
				}
			}
		}
	}


	public void saveFileEdition(String recordId, String docId, String taskId, String userId,String orgId, Map saveHistoryFile, String fileType, String isHidden, String isReview, String parentProcessInstanceId, String newInstanceid, String processName, String rootProcessInstanceId,String stampedTransferSeal) {
		List<GovDocFileEdition> listByDoc = fileEditionService.getListByDoc(docId,fileType);
		logger.info("listByDoc---------------->"+listByDoc.size());
		logger.info("saveFileEdition isHidden---------------->"+isHidden);

		logger.info("listByDoc---------------->"+listByDoc.toString());
		if (listByDoc == null || listByDoc.isEmpty()) {//是否存在历史版本
			GovDocFileEdition docFileEdition = new GovDocFileEdition();
			docFileEdition.setFileId(saveHistoryFile.get("id").toString());
			docFileEdition.setFileType(fileType);
			docFileEdition.setGoaId(docId);
			docFileEdition.setRecordId(recordId);
			docFileEdition.setVersionName(userId);
			docFileEdition.setVersionTime(new Date());
			docFileEdition.setVersionUnit(orgId);
			docFileEdition.setTextVersion(1);
			docFileEdition.setTextVersionName("V"+ 1);
			docFileEdition.setChecksum(saveHistoryFile.get("checksum").toString());
			docFileEdition.setTaskId(taskId);
			if (StringUtils.isNotEmpty(taskId)){
				docFileEdition.setTaskName(fileEditionService.getTaskName(taskId));
			}
			docFileEdition.setIsHidden(isHidden);
			docFileEdition.setIsReview(isReview);
			docFileEdition.setIsSeal(stampedTransferSeal);
			docFileEdition.setProcessId(newInstanceid);
			docFileEdition.setProcessName(processName);
			if (StringUtils.isNotEmpty(parentProcessInstanceId)){
				docFileEdition.setRootProcessId(rootProcessInstanceId);
				docFileEdition.setParentProcessId(parentProcessInstanceId);
			}else {
				docFileEdition.setRootProcessId(newInstanceid);
				docFileEdition.setParentProcessId(newInstanceid);
			}
			fileEditionService.save(docFileEdition);
		}else {
			GovDocFileEdition govDocFileEdition = listByDoc.get(0);
			logger.info("govDocFileEdition---------------->"+govDocFileEdition.toString());

			if (govDocFileEdition != null) {
				GovDocFileEdition docFileEdition = new GovDocFileEdition();
				docFileEdition.setFileId(saveHistoryFile.get("id").toString());
				docFileEdition.setFileType(fileType);
				docFileEdition.setGoaId(docId);
				docFileEdition.setRecordId(recordId);
				docFileEdition.setVersionName(userId);
				docFileEdition.setVersionTime(new Date());
				docFileEdition.setVersionUnit(orgId);
				if("0".equals(isHidden)){
					docFileEdition.setTextVersion(govDocFileEdition.getTextVersion()+1);
					docFileEdition.setTextVersionName("V"+ (govDocFileEdition.getTextVersion()+1));
				}
				docFileEdition.setChecksum(saveHistoryFile.get("checksum").toString());
				docFileEdition.setTaskId(taskId);
				if (StringUtils.isNotEmpty(taskId)){
					docFileEdition.setTaskName(fileEditionService.getTaskName(taskId));
				}
				docFileEdition.setIsHidden(isHidden);
				docFileEdition.setIsReview(isReview);
				docFileEdition.setIsSeal(stampedTransferSeal);
				docFileEdition.setProcessId(newInstanceid);
				docFileEdition.setProcessName(processName);
				if (StringUtils.isNotEmpty(parentProcessInstanceId)){
					docFileEdition.setRootProcessId(rootProcessInstanceId);
					docFileEdition.setParentProcessId(parentProcessInstanceId);
				}else {
					docFileEdition.setRootProcessId(newInstanceid);
					docFileEdition.setParentProcessId(newInstanceid);
				}
				fileEditionService.save(docFileEdition);
			}
		}
	}


    /**
     * 获取发文状态
     * @param businessKey
     * @return
     */
    public String getFlowStatus(String businessKey) {
        String result="";
        Map<String, Object> paramMap = new HashMap<String, Object>();
        Map<String, Object> map = new HashMap<String, Object>();
        paramMap.put("businessKey", businessKey);
        StringBuffer sql = new StringBuffer();
        sql.append(" SELECT EXT_PROCESSSTATUS processstatus FROM ACT_HI_PROCINST WHERE BUSINESS_KEY_ =:businessKey ");
        List<Map> list = super.findByListNativeQuery(sql.toString(),"", paramMap);
        if (list != null && !list.isEmpty()) {
            result=StringUtils.null2String(list.get(0).get("processstatus"));
        }
        return result;
    }


    /**
     *
     * @param wh
     * @return
     */
    public String convertDocumentNumber(String wh) {
        // 正则表达式匹配两种格式：文号〔年份〕第X期 或 文号〔年份〕X号
        Pattern pattern = Pattern.compile("^(.*?)〔(\\d{4})〕(?:第(\\d+)期|(\\d+)号)$");
        Matcher matcher = pattern.matcher(wh);
        if (matcher.find()) {
            String docName = matcher.group(1);
            String year = matcher.group(2);
            String number = matcher.group(3) != null ? matcher.group(3) : matcher.group(4);
            String suffix = matcher.group(3) != null ? "期" : "号";
            String prefix = matcher.group(3) != null ? "第" : "";
            return String.format("(%s)〔%s〕%s|%s|%s", docName, year, prefix, number, suffix);
        }
        return wh;
    }


    /**
     *
     * @param str
     * @return
     */
    public String convertIssuedNumerToWh(String str) {
        String wh = "";
        String jgdz = "";
        String newStr = "";
        String nf = "";
        String hm = "";

        if (StringUtils.isNoneEmpty(str)) {
            //机关代子，年份，号码
            if (str.indexOf("]") > -1) {//不显示文号名
                newStr = str.split("]")[1];
                jgdz = str.split("]")[0].replace("[", "");
                if (newStr.indexOf('-') > -1) {//不显示年份
                    nf = newStr.split("-")[1];
                    hm = newStr.split("-")[2];
                    if (hm.indexOf("|") > -1) {
                        hm = hm.split("\\|")[1];
                    }
                } else {
                    hm = newStr.split("〕")[1];
                    if (hm.indexOf("|") > -1) {
                        hm = hm.split("\\|")[1];
                    }
                    nf = newStr.split("〕")[0].split("〔")[1];
                }
            } else if (str.indexOf(')') > -1) {//显示文号名
                jgdz = str.split("\\)")[0].replace("(", "");
                newStr = str.split("\\)")[1];
                if (newStr.indexOf('-') > -1) {//不显示年份
                    nf = newStr.split("-")[1];
                    hm = newStr.split("-")[2];
                    if (hm.indexOf("|") > -1) {
                        hm = hm.split("\\|")[1];
                    }
                } else {
                    hm = newStr.split("〕")[1];
                    if (hm.indexOf("|") > -1) {
                        hm = hm.split("\\|")[1];
                    }
                    nf = newStr.split("〕")[0].split("〔")[1];
                }
            }
            wh = jgdz+"〔"+nf+"〕"+hm+"号";
        }
        return wh;
    }

	/**
	 *
	 * @param issueNum
	 * @return
	 */
	public String getFileNoIdByWh(String issueNum){
		Map paramMap = new HashMap();
		String fileNoId = "";
		String jgdz = this.convertIssuedNumerToWh(issueNum).split("〔")[0];
		String sql  = " select id from  goa_doc_sendfile_no where name = :jgdz ";
		paramMap.put("jgdz", jgdz);
		List<Map> list = super.findByListNativeQuery(sql, "",paramMap);
		if(CollectionUtils.isNotEmpty(list)) {
			fileNoId = String.valueOf(list.get(0).get("id"));
		}
		return fileNoId;
	}
}
